Solve LeetCode problem Reverse Linked List

In this blog, we'll be solving the Reverse Linked List problem on LeetCode.

The Approach

The goal is to reverse a given linked list, transforming it from its original order to the reverse order.

Step 1: Check Base Cases

We start by checking if the linked list is either empty or contains only one node. If so, there's no need to reverse it, and we return the original list.

Step 2: Initialization

We initialize three pointers: prevNode, nextNode, and temp.

  • prevNode: Initially points to the head of the linked list.
  • nextNode: Points to the next node after prevNode.
  • temp: Temporary pointer to hold the next node in the list.

Step 3: Reversing the List

While there's a nextNode present:

  1. Store the nextNode's next pointer in temp.
  2. Update nextNode's next pointer to point back to prevNode, reversing the pointer direction.
  3. Move prevNode and nextNode pointers one step forward:
    • Update prevNode to the current nextNode.
    • Update nextNode to the stored temp value.

Step 4: Final Result

Repeat the process until there are no more nodes left to traverse (nextNode becomes null). At this point, prevNode will be pointing to the new head of the reversed list.

The JavaScript Solution

Here's the JavaScript solution implementing the above steps:

1var reverseList = function (head) {
2 if (!head || !head.next) return head
3
4 let prevNode = head
5 let nextNode = prevNode.next
6 prevNode.next = null
7
8 while (nextNode) {
9 const temp = nextNode.next
10 nextNode.next = prevNode
11 prevNode = nextNode
12 nextNode = temp
13 }
14
15 return prevNode
16}

Shameless Plug

I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.

That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.

Contacts

Blogs you might want to read:

Videos might you might want to watch:

Previous PostSolve LeetCode problem Merge Two Sorted Lists
Next PostSolve Maximum Depth of Binary Tree problem in Javascript