forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
swap_nodes.py
75 lines (61 loc) · 1.66 KB
/
swap_nodes.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
class Node:
def __init__(self, data):
self.data = data;
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
while temp is not None:
print(temp.data)
temp = temp.next
# adding nodes
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# swapping nodes
def swapNodes(self, d1, d2):
prevD1 = None
prevD2 = None
if d1 == d2:
return
else:
# find d1
D1 = self.head
while D1 is not None and D1.data != d1:
prevD1 = D1
D1 = D1.next
# find d2
D2 = self.head
while D2 is not None and D2.data != d2:
prevD2 = D2
D2 = D2.next
if D1 is None and D2 is None:
return
# if D1 is head
if prevD1 is not None:
prevD1.next = D2
else:
self.head = D2
# if D2 is head
if prevD2 is not None:
prevD2.next = D1
else:
self.head = D1
temp = D1.next
D1.next = D2.next
D2.next = temp
# swapping code ends here
if __name__ == '__main__':
list = Linkedlist()
list.push(5)
list.push(4)
list.push(3)
list.push(2)
list.push(1)
list.print_list()
list.swapNodes(1, 4)
print("After swapping")
list.print_list()