I'm working on the following problem Reverse Linked List from Leetcode:
Given the head of a singly linked list, reverse the list, and return the reversed list.
Class
ListNodedefined as follows:public class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } }
Here is the solution that I came up with.
class Solution {
public ListNode reverseList(ListNode head) {
if (head != null) {
ListNode pre = head;
ListNode cur = head.next;
ListNode temp;
while (cur != null) {
temp = cur.next;
cur.next = pre;
pre = pre.next; //here should be pre = cur; but I don't get it.
cur = temp;
}
head.next = null;
return pre;
} else {
return null;
}
}
}
To make it working inside the while-loop, I need change
pre = pre.next;
with
pre = cur;
But I still don't fully understand it.
After temp = cur.next;, variable pre should still be pointing to cur, right?
So what's wrong here? Can someone explain it in detail?