DEV Community

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

Posted on

[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

Top comments (0)