Categories
Learning Technology

Solving Problem: Reverse a Linked List

Data Structures – Linked List

Problem Statement:

You are given a Linked List. Reverse the Linked List.

Example 1:

Input:

1 -> 2 -> 3 -> 4 -> 5 -> NULL

Expected Output:

5 -> 4 -> 3 -> 2 -> 1 -> NULL

Solution:

Python:

Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
def reverse_list(head):
prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
def print_list(node):
while node:
print(node.data, end=" -> ")
node = node.next
print("NULL")
# Example usage
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
print("Given Linked List:")
print_list(head)
reversed_head = reverse_list(head)
print("Reversed Linked List:")
print_list(reversed_head)

Output:

Priyanka B.'s avatar

By Priyanka B.

Hello and welcome to my little corner of internet!! I am a techie. I am very interested to discover and innovate new advances in science and technology. Blogging is one of my hobbies which I think is very useful for broadening my knowledge horizons and help me grow my skills. Apart from blogging I have also little taste in artistic skills and literature, which can keep my writing and posts tangy.

Whether you stumbled in by chance or came here on purpose, I hope you find something that sparks your curiosity or makes you think a little deeper. Thanks for stopping by!!

Leave a comment