File tree Expand file tree Collapse file tree 1 file changed +22
-25
lines changed
Expand file tree Collapse file tree 1 file changed +22
-25
lines changed Original file line number Diff line number Diff line change 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
5250llist = LinkedList ()
53-
54- # The constructed linked list is:
55- # 1->2->3->4->5->6->7
51+
5652llist .push (7 )
5753llist .push (6 )
5854llist .push (5 )
5955llist .push (4 )
6056llist .push (3 )
6157llist .push (2 )
6258llist .push (1 )
59+
6360print ("Linked list before calling swapNodes(4,3) " )
6461llist .printList ()
6562llist .swapNodes (4 , 3 )
You can’t perform that action at this time.
0 commit comments