Add 1 to a number represented as linked list | Linked list node ; Function to create a new node with given data ; Recursively add 1 from end to beginning and returns carry after all nodes are processed . ; If linked list is empty , then return carry ; Add carry returned be next node call ; Update data and return new carry ; This function mainly uses addWithCarry ( ) . ; Add 1 to linked list from end to beginning ; If there is carry after processing all nodes , then we need to add a new node to linked list ; New node becomes head now ; A utility function to print a linked list ; Driver code
class Node { constructor ( ) { this . data = 0 ; this . next = null ; } } function newNode ( data ) { var new_node = new Node ( ) ; new_node . data = data ; new_node . next = null ; return new_node ; } function addWithCarry ( head ) { if ( head == null ) return 1 ; var res = head . data + addWithCarry ( head . next ) ; head . data = res % 10 ; return parseInt ( res / 10 ) ; } function addOne ( head ) { var carry = addWithCarry ( head ) ; var newNodes = null ; if ( carry > 0 ) { newNodes = newNode ( carry ) ; newNodes . next = head ; return newNodes ; } return head ; } function printList ( node ) { while ( node != null ) { document . write ( node . data ) ; node = node . next ; } document . write ( " " ) ; } var head = newNode ( 1 ) ; head . next = newNode ( 9 ) ; head . next . next = newNode ( 9 ) ; head . next . next . next = newNode ( 9 ) ; document . write ( " " ) ; printList ( head ) ; head = addOne ( head ) ; document . write ( " " ) ; document . write ( " " ) ; printList ( head ) ;