LeetCode #206 Reverse Linked List Solution & Explanation

LeetCode Problem

Given the head of a singly linked list, reverse the list, and return the reversed list.

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?


Solution

In my initial attempt, I stored the values of the linked list in a list.

Then, I utilized the built-in function “Reverse” to reverse the list.

Finally reconstructed the linked list based on the reversed values.

C# Solution

Solution1 – Easiest but not the best

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null) 
        {
            return null;
        }

        List<int>list = new List<int>();
        
        while(head!=null)
        {
            list.Add(head.val);
            head = head.next;
        }

        list.Reverse();

        ListNode resNode = new ListNode();
        
        resNode.val = list[0];
        ListNode lastNode = resNode;
        ListNode nowNode = null;
        
        for(int i = 1; i<list.Count;i++)
        {
            nowNode = new ListNode();
            nowNode.val = list[i];
            lastNode.next = nowNode;
            
            lastNode = nowNode;
        }

        return resNode;
    }
}

When the size of the linked list becomes larger, the Reverse operation will take longer time.

Solution2 – finish without using extra space

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null) 
        {
            return null;
        }

        ListNode prev = null;
        ListNode curr = head;

        while (curr != null) 
        {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }

        return prev;
    }
}

Java Solution

Solution1

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) 
        {
            return null;
        }

        List<Integer> list = new ArrayList<>();

        while (head != null) 
        {
            list.add(head.val);
            head = head.next;
        }

        Collections.reverse(list);

        ListNode resNode = new ListNode(list.get(0));
        ListNode lastNode = resNode;
        ListNode nowNode = null;

        for (int i = 1; i < list.size(); i++)
         {
            nowNode = new ListNode(list.get(i));
            lastNode.next = nowNode;
            lastNode = nowNode;
        }

        return resNode;
    }
}

Solution2

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) 
        {
            return null;
        }

        ListNode prev = null;
        ListNode curr = head;

        while (curr != null) 
        {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }

        return prev;
    }
}

Python3 Solution

Solution1

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head:
            return None

        list = []
        while head:
            list.append(head.val)
            head = head.next

        list.reverse()

        resNode = ListNode(list[0])
        lastNode = resNode
        nowNode = None

        for i in range(1, len(list)):
            nowNode = ListNode(list[i])
            lastNode.next = nowNode
            lastNode = nowNode

        return resNode

Solution2

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head:
            return None

        prev = None
        curr = head

        while curr:
            next_node = curr.next
            curr.next = prev
            prev = curr
            curr = next_node

        return prev

JavaScript Solution

Solution1

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    if (!head) 
    {
        return null;
    }

    let arr = [];
    while (head) 
    {
        arr.push(head.val);
        head = head.next;
    }

    arr.reverse();

    let resNode = new ListNode(arr[0]);
    let lastNode = resNode;
    let nowNode = null;

    for (let i = 1; i < arr.length; i++) 
    {
        nowNode = new ListNode(arr[i]);
        lastNode.next = nowNode;
        lastNode = nowNode;
    }

    return resNode;
};

Solution2

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    if (!head) 
    {
        return null;
    }

    let prev = null;
    let curr = head;

    while (curr) 
    {
        let nextNode = curr.next;
        curr.next = prev;
        prev = curr;
        curr = nextNode;
    }

    return prev;
};

Conclusion

🧡If my solution helps, that is my honor!

🧡You can support me by clicking some ad or sharing my posts, thanks a lot

If you got any problem about the explanation, please feel free to let me know

The problem link : Reverse Linked List – LeetCode

Some Random post

Leave a Reply

Your email address will not be published. Required fields are marked *