Move all occurrences of an element to end in a linked list | C ++ code to remove key element to end of 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; struct Node * newNode ( int x ) { Node * temp = new Node ; temp -> data = x ; temp -> next = NULL ; } Node * keyToEnd ( Node * head , int key ) { Node * tail = head ; if ( head == NULL ) { return NULL ; } while ( tail -> next != NULL ) { tail = tail -> next ; } Node * last = tail ; Node * current = head ; Node * prev = NULL ; Node * prev2 = NULL ; while ( current != tail ) { if ( current -> data == key && prev2 == NULL ) { prev = current ; current = current -> next ; head = current ; last -> next = prev ; last = last -> next ; last -> next = NULL ; prev = NULL ; } else { if ( current -> data == key && prev2 != NULL ) { prev = current ; current = current -> next ; prev2 -> next = current ; last -> next = prev ; last = last -> next ; last -> next = NULL ; } else if ( current != tail ) { prev2 = current ; current = current -> next ; } } } return head ; } void printList ( Node * head ) { struct Node * temp = head ; while ( temp != NULL ) { printf ( " % d ▁ " , temp -> data ) ; temp = temp -> next ; } printf ( " STRNEWLINE " ) ; } int main ( ) { Node * root = newNode ( 5 ) ; root -> next = newNode ( 2 ) ; root -> next -> next = newNode ( 2 ) ; root -> next -> next -> next = newNode ( 7 ) ; root -> next -> next -> next -> next = newNode ( 2 ) ; root -> next -> next -> next -> next -> next = newNode ( 2 ) ; root -> next -> next -> next -> next -> next -> next = newNode ( 2 ) ; int key = 2 ; cout << " Linked ▁ List ▁ before ▁ operations ▁ : " ; printList ( root ) ; cout << " Linked List after operations : " root = keyToEnd ( root , key ) ; printList ( root ) ; return 0 ; }