Move all occurrences of an element to end in a linked list | Linked List node ; A urility function to create a new node . ; Utility function to print the elements in Linked list ; Moves all occurrences of given key to end of linked list . ; Keeps track of locations where key is present . ; Traverse list ; If current pointer is not same as pointer to a key location , then we must have found a key in linked list . We swap data of pCrawl and pKey and move pKey to next position . ; Find next position where key is present ; Moving to next Node ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def newNode ( x ) : NEW_LINE INDENT temp = Node ( 0 ) NEW_LINE temp . data = x NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( temp . data , end = " ▁ " ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def moveToEnd ( head , key ) : NEW_LINE INDENT pKey = head NEW_LINE pCrawl = head NEW_LINE while ( pCrawl != None ) : NEW_LINE INDENT if ( pCrawl != pKey and pCrawl . data != key ) : NEW_LINE INDENT pKey . data = pCrawl . data NEW_LINE pCrawl . data = key NEW_LINE pKey = pKey . next NEW_LINE DEDENT if ( pKey . data != key ) : NEW_LINE INDENT pKey = pKey . next NEW_LINE DEDENT pCrawl = pCrawl . next NEW_LINE DEDENT return head NEW_LINE DEDENT head = newNode ( 10 ) NEW_LINE head . next = newNode ( 20 ) NEW_LINE head . next . next = newNode ( 10 ) NEW_LINE head . next . next . next = newNode ( 30 ) NEW_LINE head . next . next . next . next = newNode ( 40 ) NEW_LINE head . next . next . next . next . next = newNode ( 10 ) NEW_LINE head . next . next . next . next . next . next = newNode ( 60 ) NEW_LINE print ( " Before moveToEnd ( ) , the Linked list is " ) NEW_LINE printList ( head ) NEW_LINE key = 10 NEW_LINE head = moveToEnd ( head , key ) NEW_LINE print ( " After moveToEnd ( ) , the Linked list is " ) NEW_LINE printList ( head ) NEW_LINE