-
Notifications
You must be signed in to change notification settings - Fork 369
/
Copy pathReverse a singly linked list.py
102 lines (51 loc) · 1.64 KB
/
Reverse a singly 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
Reversing a linked list using iterative approach
#node of singly linked list
class Node:
#constructor used to initialize the node object
def __init__(self, value):
self.value = value
self.next = None
class l_list:
#head initialization
def __init__(self):
self.head = None
self.l_node = None
# inserting a new node at the beginning
def append(self,value):
if self.l_node is None:
self.head = Node(value)
self.l_node = self.head
else:
self.l_node.next = Node(value)
self.l_node = self.l_node.next
#function to print the linkedlist
def show(self):
c=self.head
while c:
print(c.value, end=' ')
c=c.next
#function to reverse the linked list
def reverse(linked_list):
prev = None
c = linked_list.head
if c is None:
return
after = c.next
while after:
c.next = prev
prev = c
c = after
after = after.next
c.next = prev
linked_list.head = c
#driver code
linked_list = l_list()
a=int(input("Enter number of elements of linked list: "))
print("Enter data of linked list one at a time: ")
for i in range(a):
value=int(input())
linked_list.append(value)
reverse(linked_list)
print("The reversed linked list is: ")
linked_list.show()
Time Complexity of reversing a linked list is O(n)