DEV Community

Cover image for [LeetCode] Visualization of Reverse Linked List
Yuko
Yuko

Posted on

1

[LeetCode] Visualization of Reverse Linked List

This is my memo when I solved 206. Reverse Linked List.

What we want

This is pretty simple. We want to re-order a provided linked list in the opposite direction.

Strategy

Go through each element and replace the value of next from the next element’s address with the previous element’s.

This requires us to handle two operations: 1) changing the value of next of each element and 2) tracking which element we’re updating and what element comes next.

what we want to do in each round

Code

I think there are two tricky things when it comes to coding: 1) storing the next element to modify before updating curr.next, and 2) returning prev instead of curr as we update curr at the last of the while loop.

the last round of the while loop



    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     val: number
     *     next: ListNode | null
     *     constructor(val?: number, next?: ListNode | null) {
     *         this.val = (val===undefined ? 0 : val)
     *         this.next = (next===undefined ? null : next)
     *     }
     * }
     */

    function reverseList(head: ListNode | null): ListNode | null {
        let [prev, curr] = [null, head]
        while(curr){
          const next = curr.next
          curr.next = prev
          prev = curr
          curr = next
        }
        return prev

    };


Enter fullscreen mode Exit fullscreen mode

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

👋 Kindness is contagious

If you found this post useful, consider leaving a ❤️ or a nice comment!

Got it