Skip to main content

Reverse Linked List

Question

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

Example 1
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Solution

all//Reverse Linked List.py


# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None

class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# Initialize the prev and current node
prev = None
curr = head

# Loop through the list
while curr:
# Store the next node
next_node = curr.next
# Reverse the link by pointing current node to the prev node
curr.next = prev
# Update the prev node and current node
prev = curr
curr = next_node
# Return the prev node which is the head of the reversed list
return prev