Move all occurrences of an element to end in a linked list | 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 Node { constructor ( ) { this . data = 0 ; this . next = null ; } } function newNode ( x ) { var temp = new Node ( ) ; temp . data = x ; temp . next = null ; return temp ; } function printList ( head ) { var temp = head ; while ( temp != null ) { document . write ( temp . data + " " ) ; temp = temp . next ; } document . write ( " " ) ; } function moveToEnd ( head , key ) { var pKey = head ; var 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 ; } } var 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 ) ; document . write ( " " ) ; printList ( head ) ; var key = 10 ; moveToEnd ( head , key ) ; document . write ( " " ) ; printList ( head ) ;