Move all occurrences of an element to end in a linked list | A Linked list Node ; Function to remove key to end ; Node to keep pointing to tail ; Node to point to last of linked list ; Node prev2 to point to previous when head . data != key ; Loop to perform operations to remove key to end ; Function to display linked list ; 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 ( x ) NEW_LINE return temp NEW_LINE DEDENT def keyToEnd ( head , key ) : NEW_LINE INDENT tail = head NEW_LINE if ( head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT while ( tail . next != None ) : NEW_LINE INDENT tail = tail . next NEW_LINE DEDENT last = tail NEW_LINE current = head NEW_LINE prev = None NEW_LINE prev2 = None NEW_LINE while ( current != tail ) : NEW_LINE INDENT if ( current . data == key and prev2 == None ) : NEW_LINE INDENT prev = current NEW_LINE current = current . next NEW_LINE head = current NEW_LINE last . next = prev NEW_LINE last = last . next NEW_LINE last . next = None NEW_LINE prev = None NEW_LINE DEDENT else : NEW_LINE INDENT if ( current . data == key and prev2 != None ) : NEW_LINE INDENT prev = current NEW_LINE current = current . next NEW_LINE prev2 . next = current NEW_LINE last . next = prev NEW_LINE last = last . next NEW_LINE last . next = None NEW_LINE DEDENT elif ( current != tail ) : NEW_LINE INDENT prev2 = current NEW_LINE current = current . next NEW_LINE DEDENT DEDENT DEDENT return head 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 if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 5 ) NEW_LINE root . next = newNode ( 2 ) NEW_LINE root . next . next = newNode ( 2 ) NEW_LINE root . next . next . next = newNode ( 7 ) NEW_LINE root . next . next . next . next = newNode ( 2 ) NEW_LINE root . next . next . next . next . next = newNode ( 2 ) NEW_LINE root . next . next . next . next . next . next = newNode ( 2 ) NEW_LINE key = 2 NEW_LINE print ( " Linked ▁ List ▁ before ▁ operations ▁ : " ) NEW_LINE printList ( root ) NEW_LINE print ( " Linked ▁ List ▁ after ▁ operations ▁ : " ) NEW_LINE root = keyToEnd ( root , key ) NEW_LINE printList ( root ) NEW_LINE DEDENT