Swap nodes in a linked list without swapping data | Python program to swap two given nodes of a linked list ; head of list ; Function to swap Nodes x and y in linked list by changing links ; Nothing to do if x and y are same ; Search for x ( keep track of prevX and CurrX ) ; Search for y ( keep track of prevY and currY ) ; If either x or y is not present , nothing to do ; If x is not head of linked list ; make y the new head ; If y is not head of linked list ; make x the new head ; Swap next pointers ; Function to add Node at beginning of list . ; 1. alloc the Node and put the data ; 2. Make next of new Node as head ; 3. Move the head to point to new Node ; This function prints contents of linked list starting from the given Node ; Driver program to test above function ; The constructed linked list is : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
class LinkedList ( object ) : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT class Node ( object ) : NEW_LINE INDENT def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def swapNodes ( self , x , y ) : NEW_LINE INDENT if x == y : NEW_LINE INDENT return NEW_LINE DEDENT prevX = None NEW_LINE currX = self . head NEW_LINE while currX != None and currX . data != x : NEW_LINE INDENT prevX = currX NEW_LINE currX = currX . next NEW_LINE DEDENT prevY = None NEW_LINE currY = self . head NEW_LINE while currY != None and currY . data != y : NEW_LINE INDENT prevY = currY NEW_LINE currY = currY . next NEW_LINE DEDENT if currX == None or currY == None : NEW_LINE INDENT return NEW_LINE DEDENT if prevX != None : NEW_LINE INDENT prevX . next = currY NEW_LINE DEDENT else : NEW_LINE INDENT self . head = currY NEW_LINE DEDENT if prevY != None : NEW_LINE INDENT prevY . next = currX NEW_LINE DEDENT else : NEW_LINE INDENT self . head = currX NEW_LINE DEDENT temp = currX . next NEW_LINE currX . next = currY . next NEW_LINE currY . next = temp NEW_LINE DEDENT def push ( self , new_data ) : NEW_LINE INDENT new_Node = self . Node ( new_data ) NEW_LINE new_Node . next = self . head NEW_LINE self . head = new_Node NEW_LINE DEDENT def printList ( self ) : NEW_LINE INDENT tNode = self . head NEW_LINE while tNode != None : NEW_LINE INDENT print tNode . data , NEW_LINE tNode = tNode . next NEW_LINE DEDENT DEDENT DEDENT llist = LinkedList ( ) NEW_LINE llist . push ( 7 ) NEW_LINE llist . push ( 6 ) NEW_LINE llist . push ( 5 ) NEW_LINE llist . push ( 4 ) NEW_LINE llist . push ( 3 ) NEW_LINE llist . push ( 2 ) NEW_LINE llist . push ( 1 ) NEW_LINE print " Linked ▁ list ▁ before ▁ calling ▁ swapNodes ( ) ▁ " NEW_LINE llist . printList ( ) NEW_LINE llist . swapNodes ( 4 , 3 ) NEW_LINE print   " NEW_LINE Linked list after calling swapNodes ( )   " NEW_LINE llist . printList ( ) NEW_LINE