Skip to content

Commit 02712fc

Browse files
committed
add linkedlist node_swap
1 parent 3219db1 commit 02712fc

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

linked_list/node_swap.py

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
""" Swap two nodes in a linked list
2+
input: 1 -> 5 -> 2 -> 3 -> 7 -> 9 -> 10
3+
output: 1 -> 7 -> 2 -> 3 -> 5 -> 9 -> 10
4+
"""
5+
6+
class Node:
7+
""" Node class contains everything related to Linked List node """
8+
def __init__(self, data):
9+
""" initializing single node with data """
10+
self.data = data
11+
self.next = None
12+
13+
14+
class LinkedList:
15+
""" Singly Linked List is a linear data structure """
16+
def __init__(self):
17+
""" initializing singly linked list with zero node """
18+
self.head = None
19+
20+
def insert_head(self, data):
21+
""" inserts node at the start of linked list """
22+
node = Node(data)
23+
node.next = self.head
24+
self.head = node
25+
26+
def print(self):
27+
""" prints entire linked list without changing underlying data """
28+
current = self.head
29+
while current is not None:
30+
print(" ->", current.data, end="")
31+
current = current.next
32+
print()
33+
34+
35+
def swap_node(self, node1, node2):
36+
""" swap node1 with node2 """
37+
previous1 = None
38+
current1 = self.head
39+
while current1 is not None:
40+
if current1 is node1:
41+
break
42+
previous1 = current1
43+
current1 = current1.next
44+
45+
previous2 = None
46+
current2 = self.head
47+
while current2 is not None:
48+
if current2 is node2:
49+
break
50+
previous2 = current2
51+
current2 = current2.next
52+
53+
if previous1 is not None:
54+
previous1.next = current2
55+
else:
56+
self.head = current2
57+
if previous2 is not None:
58+
previous2.next = current1
59+
else:
60+
self.head = current1
61+
62+
current1.next, current2.next = current2.next, current1.next
63+
64+
65+
def main():
66+
""" operational function """
67+
linkedlist = LinkedList()
68+
linkedlist.insert_head(10)
69+
linkedlist.insert_head(9)
70+
linkedlist.insert_head(7)
71+
linkedlist.insert_head(3)
72+
linkedlist.insert_head(2)
73+
linkedlist.insert_head(5)
74+
linkedlist.insert_head(1)
75+
76+
linkedlist.print()
77+
linkedlist.swap_node(linkedlist.head.next, linkedlist.head.next.next.next.next)
78+
linkedlist.print()
79+
80+
81+
if __name__ == '__main__':
82+
main()

0 commit comments

Comments
 (0)