Skip to content

Commit 00bf317

Browse files
author
IN\abhinav.singh
committed
Swap nodes in a linked list without swapping data
1 parent d7e3cd6 commit 00bf317

File tree

1 file changed

+22
-25
lines changed

1 file changed

+22
-25
lines changed

Linked List/swapNodes.py

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,42 @@
1-
class Node:
2-
def __init__(self,data):
3-
self.data = data
1+
class Node(object):
2+
def __init__(self, d):
3+
self.data = d
44
self.next = None
55

6-
class LinkedList:
6+
class LinkedList(object):
77
def __init__(self):
88
self.head = None
99
def push(self, new_data):
10-
new_node = Node(new_data)
11-
new_node.next = self.head
12-
self.head = new_node
13-
def swapNodes(self,x,y):
10+
new_Node = Node(new_data)
11+
new_Node.next = self.head
12+
self.head = new_Node
13+
def swapNodes(self, x, y):
1414
if x == y:
1515
return
1616
prevX = None
1717
currX = self.head
18-
while (currX != None and currX.data !=x):
18+
while currX != None and currX.data != x:
1919
prevX = currX
2020
currX = currX.next
21-
2221
prevY = None
2322
currY = self.head
24-
while (currY != None and currY.data!= y):
23+
while currY != None and currY.data != y:
2524
prevY = currY
2625
currY = currY.next
27-
28-
if (currX == None) or (currY == None):
26+
27+
if currX == None or currY == None:
2928
return
30-
29+
3130
if prevX != None:
32-
prevX.next = currX
33-
else:
34-
self.head = currX
35-
36-
if prevY != None:
37-
prevY.next = currY
38-
else:
31+
prevX.next = currY
32+
else:
3933
self.head = currY
4034

35+
if prevY != None:
36+
prevY.next = currX
37+
else:
38+
self.head = currX
39+
4140
temp = currX.next
4241
currX.next = currY.next
4342
currY.next = temp
@@ -48,18 +47,16 @@ def printList(self):
4847
print(tNode.data,end=' ')
4948
tNode = tNode.next
5049

51-
# Driver program to test above function
5250
llist = LinkedList()
53-
54-
# The constructed linked list is:
55-
# 1->2->3->4->5->6->7
51+
5652
llist.push(7)
5753
llist.push(6)
5854
llist.push(5)
5955
llist.push(4)
6056
llist.push(3)
6157
llist.push(2)
6258
llist.push(1)
59+
6360
print ("Linked list before calling swapNodes(4,3) ")
6461
llist.printList()
6562
llist.swapNodes(4, 3)

0 commit comments

Comments
 (0)