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 afterprevNode
.temp
: Temporary pointer to hold the next node in the list.
Step 3: Reversing the List
While there's a nextNode
present:
- Store the
nextNode
's next pointer intemp
. - Update
nextNode
's next pointer to point back toprevNode
, reversing the pointer direction. - Move
prevNode
andnextNode
pointers one step forward:- Update
prevNode
to the currentnextNode
. - Update
nextNode
to the storedtemp
value.
- Update
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 head34 let prevNode = head5 let nextNode = prevNode.next6 prevNode.next = null78 while (nextNode) {9 const temp = nextNode.next10 nextNode.next = prevNode11 prevNode = nextNode12 nextNode = temp13 }1415 return prevNode16}
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
- Email: thatanjan@gmail.com
- LinkedIn: @thatanjan
- Portfolio: anjan
- Github: @thatanjan
- Instagram : @thatanjan
- Twitter: @thatanjan
Blogs you might want to read:
- Eslint, prettier setup with TypeScript and react
- What is Client-Side Rendering?
- What is Server Side Rendering?
- Everything you need to know about tree data structure
- 13 reasons why you should use Nextjs
- Beginners guide to quantum computers
Videos might you might want to watch: