DEV Community


Posted on

Reverse a Linked List - Leetcode

I'm sure many of you have seen this problem: reverse a linked list. When you reverse a linked list, you are essentially reversing the direction the linked list goes from.
For example, if you have a linked list 1 -> 2 -> 3 -> 4, you want to make the linked list 1 <- 2 <- 3 <- 4.
To do this, you need a variable prev that you can set the previous value to.
Here's my code for this problem:

def reverseList(head):
        prev = None
        while head:
            temp = head
            head =
   = prev
            prev = temp
        return prev
Enter fullscreen mode Exit fullscreen mode

You first set the variable prev to None. Then you create a while loop that loops through head, which contains the first value of the linked list. You set a temp variable equal to the current node. Then you set the current node to the next node to progress through the linked list, while temp remains the current node. You set the next pointer of temp(current) equal to prev, which is at first None, but then it equals the current node afterwards. Then you repeat.
For example, using 1 -> 2 -> 3 -> 4
temp = 1
head = 2
prev = 1
temp = 2
head = 3
prev = 2
temp = 3
head = 4
prev = 3
And that's how you reverse the linked list.

Top comments (0)