Reverse a linked list, this is a hard question, if you follow these four steps in order, in any code solution you will solve it. The blueprint take away is this:
1 = 2.3
2.3 = 4
4 = 3
2 = 1return = 4
Even though I am posting the answer here, as with any maths formula or code, it doesn’t make sense unless you know what that summary is about.
I have labelled the numbers, instead of the variable names or prev(4), temp(1), head(2) and next(3), and like the 3 cup game swapping the cups over the orb, it is easier to remember the variable names as numbers, but write your code as prev instead of 4 etc in your code solution. In addition to the LeetCode diagram, the numbers in the vertices have nothing to do with the variable names.
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]public class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
while(head != null){
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
// ln 4 = null
//while 2 not equal null
//ln 1 = 2.3
//2.3 = 4
//4 = 3
//2 = 1
//ret 4 }
return prev;
}
}