206. Reverse Linked List
# Easy

Solution
temp
records next node, head
is current node, preNode
is the pre-node of head
. Don't forget to initialise preNode = NULL
, return new head.
temp
记录下一个节点,head
表示当前节点,preNode
表示head
的母节点。必须初始化preNode=NULL
,并且最后返回新的头节点(即最后一个节点)。
record next node temporally
let head.next point to preNode
move to next node
暂时记录下一个节点
让head.next指向前一个节点
指针后移一位
Python syntax
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode pre = null;
ListNode curr = new ListNode();
curr = head;
while(curr != null) {
ListNode nextTemp = curr.next;
curr.next = pre;
pre = curr;
curr = nextTemp;
}
return pre;
}
}
Last updated
Was this helpful?