Skip to content

Commit c95f9ce

Browse files
authored
Merge pull request #95 from Iamtripathisatyam/master
Created a Swap Nodes of Linked List without Swapping data code in Python
2 parents 50d3fbf + 66cb99c commit c95f9ce

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
"""
2+
Given a linked list and two keys in it, swap nodes for two given keys.
3+
Nodes should be swapped by changing links.
4+
Swapping data of nodes may be expensive in many situations
5+
when data contains many fields.
6+
"""
7+
8+
9+
"""
10+
Input: 8 -> 5 -> 10 -> 7 -> 6 -> 11 -> 9 -> None, key1 = 8, key2 = 5
11+
Output: 5 -> 8 -> 10 -> 7 -> 6 -> 11 -> 9 -> None4
12+
13+
"""
14+
15+
# Class to create new Node
16+
17+
18+
class Node:
19+
def __init__(self, data):
20+
self.data = data
21+
self.next = None
22+
23+
24+
class Linked_List:
25+
def __init__(self):
26+
self.head = None
27+
28+
# Function to add the data at the end of linked list
29+
def Insert_At_End(self, new_data):
30+
new_node = Node(new_data) # Allocate the new node and put the data
31+
if self.head is None: # if list is empty then retrun
32+
self.head = new_node
33+
return
34+
current = self.head
35+
while(current.next):
36+
current = current.next
37+
current.next = new_node # Move new node to the next of current node
38+
39+
# Fucntion to swap nodes key1 and key2 in linked list by changing links
40+
def Swap(self, key1, key2):
41+
Prev_node_1 = None
42+
Prev_node_2 = None
43+
Node_1 = self.head
44+
Node_2 = self.head
45+
if self.head == None:
46+
return
47+
48+
if key1 == key2: # Nothing to do if key1 and key2 are same
49+
return
50+
while(Node_1.data != key1): # Search for key 1
51+
Prev_node_1 = Node_1
52+
Node_1 = Node_1.next
53+
while(Node_2.data != key2): # Search for key 2
54+
Prev_node_2 = Node_2
55+
Node_2 = Node_2.next
56+
if Prev_node_1 is not None:
57+
Prev_node_1.next = Node_2
58+
else:
59+
self.head = Node_2
60+
if Prev_node_2 is not None:
61+
Prev_node_2.next = Node_1
62+
else:
63+
self.head = Node_1
64+
temp = Node_1.next
65+
Node_1.next = Node_2.next
66+
Node_2.next = temp
67+
# Function to print the data to the screen
68+
69+
def Display(self):
70+
temp = self.head
71+
while(temp):
72+
print(temp.data, "->", end=" ")
73+
temp = temp.next
74+
print("None")
75+
76+
77+
if __name__ == "__main__":
78+
L_list = Linked_List()
79+
L_list.Insert_At_End(8)
80+
L_list.Insert_At_End(5)
81+
L_list.Insert_At_End(10)
82+
L_list.Insert_At_End(7)
83+
L_list.Insert_At_End(6)
84+
L_list.Insert_At_End(11)
85+
L_list.Insert_At_End(9)
86+
print("Linked List: ")
87+
L_list.Display()
88+
print("Swap List: ")
89+
L_list.Swap(8, 5)
90+
L_list.Display()

0 commit comments

Comments
 (0)