Move all occurrences of an element to end in a linked list | Node class javascript code to remove key element to end of linked list ; Function to remove key to end ; Node to keep pointing to tail ; Node to povar to last of linked list ; Node prev2 to povar to previous when head . data != key ; loop to perform operations to remove key to end ; Function to display linked list ; Driver Code
class Node { constructor ( val ) { this . data = val ; this . next = null ; } } var root ; function keyToEnd ( head , key ) { var tail = head ; if ( head == null ) { return null ; } while ( tail . next != null ) { tail = tail . next ; } var last = tail ; var current = head ; var prev = null ; var 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 ; } function display ( root ) { while ( root != null ) { document . write ( root . data + " " ) ; root = root . next ; } } root = new Node ( 5 ) ; root . next = new Node ( 2 ) ; root . next . next = new Node ( 2 ) ; root . next . next . next = new Node ( 7 ) ; root . next . next . next . next = new Node ( 2 ) ; root . next . next . next . next . next = new Node ( 2 ) ; root . next . next . next . next . next . next = new Node ( 2 ) ; var key = 2 ; document . write ( " " ) ; display ( root ) ; document . write ( " " ) ; root = keyToEnd ( root , key ) ; display ( root ) ;