这个就是常规操作了,使用一个变量记录前驱 pre,一个变量记录后继 next,不断更新current.next = pre 就好了。
链表的题目 90% 的 bug 都出现在:
头尾节点的处理
指针循环引用导致死循环
因此大家对这两个问题要保持 100% 的警惕。
关键点解析
链表的基本操作(交换)
虚拟节点 dummy 简化操作
注意更新 current 和 pre 的位置, 否则有可能出现溢出
代码
语言支持:JS, C++, Python,Java
JavaScript Code:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function (head) {
if (!head || !head.next) return head;
let cur = head;
let pre = null;
while (cur) {
const next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
};
C++ Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* cur = head;
ListNode* next = NULL;
while (cur != NULL) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};
Python Code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head: return None
prev = None
cur = head
while cur:
cur.next, prev, cur = prev, cur, cur.next
return prev
Java Code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next: return head
ans = self.reverseList(head.next)
head.next.next = head
head.next = None
return ans