Skip to content

Commit 6b1c75e

Browse files
Added program of reversing Linkedlist.
Program for reversing linkedlist in python.
1 parent 9629aef commit 6b1c75e

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Linkedlist_reverse.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Python program to reverse a linked list
2+
3+
4+
# Node class
5+
6+
7+
class Node:
8+
9+
# Constructor to initialize the node object
10+
def __init__(self, data):
11+
self.data = data
12+
self.next = None
13+
14+
15+
class LinkedList:
16+
17+
# Function to initialize head
18+
def __init__(self):
19+
self.head = None
20+
21+
# Function to reverse the linked list
22+
def reverse(self):
23+
prev = None
24+
current = self.head
25+
while(current is not None):
26+
next = current.next
27+
current.next = prev
28+
prev = current
29+
current = next
30+
self.head = prev
31+
32+
# Function to insert a new node at the beginning
33+
def push(self, new_data):
34+
new_node = Node(new_data)
35+
new_node.next = self.head
36+
self.head = new_node
37+
38+
# Utility function to print the LinkedList
39+
def printList(self):
40+
temp = self.head
41+
while(temp):
42+
print (temp.data,end=" ")
43+
temp = temp.next
44+
45+
46+
# Driver program to test above functions
47+
llist = LinkedList()
48+
llist.push(20)
49+
llist.push(4)
50+
llist.push(15)
51+
llist.push(85)
52+
53+
print ("Given Linked List")
54+
llist.printList()
55+
llist.reverse()
56+
print ("\nReversed Linked List")
57+
llist.printList()
58+
59+

0 commit comments

Comments
 (0)