-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreversing_Linkedlist.py
54 lines (46 loc) · 1.27 KB
/
reversing_Linkedlist.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
# for ref: https://www.youtube.com/watch?v=ugQ2DVJJroc
class Node:
def __init__(self, data=None, next=None):
self.data=data
self.next=next
class LinkedList():
def __init__(self):
self.head=None
def insert_node(self, data):
if self.head is None:
self.head=Node(data, None)
return
itr=self.head
while itr:
temp=itr.next
if temp is None:
itr.next=Node(data, None)
break
itr=itr.next
# reversing using iterative method
def reverse_LL(self):
current=self.head
prev=None
while current !=None:
temp=current.next
current.next=prev
prev=current
current=temp
self.head=prev
def print_LL(self):
if self.head is None:
print("LL is empty")
return
itr=self.head
while itr:
print(str(itr.data),end="-->")
itr=itr.next
print()
LL=LinkedList()
LL.insert_node(10)
LL.insert_node(20)
LL.insert_node(30)
LL.insert_node(40)
LL.print_LL()
LL.reverse_LL()
LL.print_LL()