按照双指针法编写代码,如下代码,结果运行的时候报错了
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return head;
if (head.next == null) return head;
ListNode cur = head.next;
ListNode pre = head;
ListNode temp = cur.next;
while (cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
分析一下:
首先链表和指针如下:
按照编写代码发现出现如下情况:
因此解决方法:使pre.next先指向空,再让cur.next=pre,这样就不会出现链表中发现循环的错误了
修改过后的代码如下:
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return head;
if (head.next == null) return head;
ListNode cur = head.next;
ListNode pre = head;
ListNode temp = cur.next;
pre.next = null;
while (cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}