Move all occurrences of an element to end in a linked list | C ++ program to move all occurrences of a given key to end . ; A 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
#include <bits/stdc++.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; struct Node * newNode ( int x ) { Node * temp = new Node ; temp -> data = x ; temp -> next = NULL ; } void printList ( Node * head ) { struct Node * temp = head ; while ( temp != NULL ) { printf ( " % d ▁ " , temp -> data ) ; temp = temp -> next ; } printf ( " STRNEWLINE " ) ; } void moveToEnd ( Node * head , int key ) { struct Node * pKey = head ; struct Node * pCrawl = head ; while ( pCrawl != NULL ) { if ( pCrawl != pKey && pCrawl -> data != key ) { pKey -> data = pCrawl -> data ; pCrawl -> data = key ; pKey = pKey -> next ; } if ( pKey -> data != key ) pKey = pKey -> next ; pCrawl = pCrawl -> next ; } } int main ( ) { Node * head = newNode ( 10 ) ; head -> next = newNode ( 20 ) ; head -> next -> next = newNode ( 10 ) ; head -> next -> next -> next = newNode ( 30 ) ; head -> next -> next -> next -> next = newNode ( 40 ) ; head -> next -> next -> next -> next -> next = newNode ( 10 ) ; head -> next -> next -> next -> next -> next -> next = newNode ( 60 ) ; printf ( " Before ▁ moveToEnd ( ) , ▁ the ▁ Linked ▁ list ▁ is STRNEWLINE " ) ; printList ( head ) ; int key = 10 ; moveToEnd ( head , key ) ; printf ( " After moveToEnd ( ) , the Linked list is " printList ( head ) ; return 0 ; }