LeetCode 206. Reverse a Linked List

Fiona L
2 min readJan 17, 2022

--

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:

Think 3 cup trick
https://www.canstockphoto.com/shell-game-three-thimbles-and-ball-54769795.html
1 = 2.3
2.3 = 4
4 = 3
2 = 1
return = 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.

Given the head of a singly linked list, reverse the list, and return the reversed list.
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;
}
}

--

--

Fiona L
0 Followers

Avid coder, enthusiast developer