forked from DSCTOCE/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_a_linked_list.py
62 lines (48 loc) · 1.48 KB
/
reverse_a_linked_list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Defination of a single node in Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Linked List Data Structure class
class LinkedList:
def __init__(self):
self.head = None
# A method to add an element
# at the beginning of the list
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# A method to print the list
def print_list(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
"""
* Given a linked list, this algorithm can be used to reverse it at O(n) time-complexity and O(1) space complexity.
* reverse_a_linked_list() takes an argument called *root* which will be a head element of the linked list.
* Swap the next node of current node with the previous node.
"""
def reverse_a_linked_list(root):
prev = None
curr = root.head
while curr is not None:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
root.head = prev
if __name__ == '__main__':
# Create a Linked List from 9 to 1
llist = LinkedList()
for i in range(1, 10):
llist.push(i)
print("-- LinkedList --")
# This will print the list from 9 to 1
llist.print_list()
print("-- Reversed LinkedList --")
# reverse list
reverse_a_linked_list(llist)
# This will print the list from 1 to 9
llist.print_list()