Skip to content

Commit 3c21c80

Browse files
committed
swap nodes using linked list
1 parent 8ee0085 commit 3c21c80

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

swap nodes in linkedlist.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class Node:
2+
def __init__(self, data):
3+
self.data = data
4+
self.next = None
5+
6+
class Linkedlist:
7+
def __init__(self):
8+
self.head = None
9+
10+
def printList(self):
11+
temp = self.head
12+
while temp is not None:
13+
print(temp.data)
14+
temp = temp.next
15+
16+
def swap_node(self, key_1, key_2):
17+
if key_1 == key_2:
18+
return
19+
prev_1 = None
20+
curr_1 = self.head
21+
while curr_1 and curr_1.data != key_1:
22+
prev_1 = curr_1
23+
curr_1 = curr_1.next
24+
prev_2 = None
25+
curr_2 = self.head
26+
while curr_2 and curr_2.data != key_2:
27+
prev_2 = curr_2
28+
curr_2 = curr_2.next
29+
if not curr_1 or not curr_2:
30+
return
31+
if prev_1:
32+
prev_1.next = curr_2
33+
else:
34+
self.head = curr_2
35+
if prev_2:
36+
prev_2.next = curr_1
37+
else:
38+
self.head = curr_1
39+
curr_1.next, curr_2.next = curr_2.next, curr_1.next
40+
41+
42+
if __name__ == '__main__':
43+
list1 = Linkedlist()
44+
list1.head = Node("mon")
45+
l2 = Node("tue")
46+
l3 = Node("wed")
47+
list1.head.next = l2
48+
l2.next = l3
49+
list1.printList()
50+
list1.swap_node("mon", "tue")
51+
print(" After swapping nodes: ")
52+
list1.printList()

0 commit comments

Comments
 (0)