使用方法:迭代
思路:(基础思路)
定义两个指针:双指针 + 临时指针
规范解法:
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){return null;}
else{
ListNode pre = null;
ListNode cur = head;
while(cur!= null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
}
不规范解法
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){return head;}
else{
ListNode temp ;
ListNode newhead = head;
head = head.next;
newhead.next = null;
while(head != null){
temp = head;
head = head.next;
temp.next = newhead;
newhead = temp;
}
return newhead;
}
}
}
易错点:
cur.next = pre;执行后,cur所在节点指向pre,如果此时用临时指temp记录cur,则temp.next 是指向pre的,所以并不能记住cur节点的下一个节点的位置,导致程序形成闭环,直接崩溃!!!!!!!!
所以:正确的过程是:
先用temp记录cur节点的下一节点的位置 ListNode temp = cur.next;
cur指针反转指向pre cur.next = pre;
将cur节点的位置赋给pre pre = cur
最后将temp节点的位置赋给cur cur = temp;(可以发现,最后两次置换操作根本没使用.next就是因为指针的指向发生了变化)
(改变指针只想谁,对对象的本身做了改变)