/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode Left=null;
ListNode Right =head;
while(head != null){
Right=head.next;
head.next =Left;
Left=head;
head=Right;
}
return Left;
}
}
注意: while 中条件是 while(head != null)
如果是while(head.next != null) 则反转不了最后一个节点
最后应return Left 而不是return head
走到最后一个节点时,Right 指向了 null; head.next =Left 反转,Left 指向了head , head = Right也指向了Null
所以返回left