File tree 1 file changed +75
-0
lines changed
data_structures/linked_list
1 file changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node :
2
+ def __init__ (self , data ):
3
+ self .data = data ;
4
+ self .next = None
5
+
6
+
7
+ class Linkedlist :
8
+ def __init__ (self ):
9
+ self .head = None
10
+
11
+ def print_list (self ):
12
+ temp = self .head
13
+ while temp is not None :
14
+ print (temp .data )
15
+ temp = temp .next
16
+
17
+ # adding nodes
18
+ def push (self , new_data ):
19
+ new_node = Node (new_data )
20
+ new_node .next = self .head
21
+ self .head = new_node
22
+
23
+ # swapping nodes
24
+ def swapNodes (self , d1 , d2 ):
25
+ prevD1 = None
26
+ prevD2 = None
27
+ if d1 == d2 :
28
+ return
29
+ else :
30
+ # find d1
31
+ D1 = self .head
32
+ while D1 is not None and D1 .data != d1 :
33
+ prevD1 = D1
34
+ D1 = D1 .next
35
+ # find d2
36
+ D2 = self .head
37
+ while D2 is not None and D2 .data != d2 :
38
+ prevD2 = D2
39
+ D2 = D2 .next
40
+ if D1 is None and D2 is None :
41
+ return
42
+ # if D1 is head
43
+ if prevD1 is not None :
44
+ prevD1 .next = D2
45
+ else :
46
+ self .head = D2
47
+ # if D2 is head
48
+ if prevD2 is not None :
49
+ prevD2 .next = D1
50
+ else :
51
+ self .head = D1
52
+ temp = D1 .next
53
+ D1 .next = D2 .next
54
+ D2 .next = temp
55
+
56
+ # swapping code ends here
57
+
58
+
59
+
60
+ if __name__ == '__main__' :
61
+ list = Linkedlist ()
62
+ list .push (5 )
63
+ list .push (4 )
64
+ list .push (3 )
65
+ list .push (2 )
66
+ list .push (1 )
67
+
68
+ list .print_list ()
69
+
70
+ list .swapNodes (1 , 4 )
71
+ print ("After swapping" )
72
+ list .print_list ()
73
+
74
+
75
+
You can’t perform that action at this time.
0 commit comments