Move all occurrences of an element to end in a linked list | Java 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
class GFG { static class Node { int data ; Node next ; } static Node newNode ( int x ) { Node temp = new Node ( ) ; temp . data = x ; temp . next = null ; return temp ; } static void printList ( Node head ) { Node temp = head ; while ( temp != null ) { System . out . printf ( " % d ▁ " , temp . data ) ; temp = temp . next ; } System . out . printf ( "NEW_LINE"); } static void moveToEnd ( Node head , int key ) { Node pKey = head ; 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 ; } } public static void main ( String args [ ] ) { 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 ) ; System . out . printf ( "Before moveToEnd(), the Linked list isNEW_LINE"); printList ( head ) ; int key = 10 ; moveToEnd ( head , key ) ; System . out . printf ( " After moveToEnd ( ) , the Linked list is "); printList ( head ) ; } }