Given a natural number in the form of a linked list, add 1 to it.
Example: Linked List: 7β8β9
Output: Linked List: 7β9β0
Approach Reverse Linked List
Reverse given linked list for example, 1-> 9-> 9 -> 9 is converted to 9-> 9 -> 9 ->1.For this changed linked list now traverse the list, in the left-most node add one. if this nodeβs value is equal to 9 then propagate a carry to the next Node. Do the same procedure until the carry is there. Reverse the string back as in original form and then returned the head to get the string printed.
#include <iostream> using namespace std; //n=next node ; d=data ; p= previous node; h=head node; c=current node class Node { public: int d; Node* n; }; Node *newNode(int d) { Node *new_node = new Node; new_node->d = d; new_node->n = NULL; return new_node; } Node *reverse(Node *h) { Node * p = NULL; Node * c = h; Node * n; while (c != NULL) { n = c->n; c->n = p; p = c; c = n; } return p; } Node *addOneUtil(Node *h) { Node* res = h; Node *temp, *p = NULL; int carry = 1, sum; while (h != NULL) { sum = carry + h->d; carry = (sum >= 10)? 1 : 0; sum = sum % 10; h->d = sum; temp = h; h = h->n; } if (carry > 0) temp->n = newNode(carry); return res; } Node* addOne(Node *h) { h = reverse(h); h = addOneUtil(h); return reverse(h); } int main() { Node *h = newNode(1); h->n = newNode(9); h->n->n = newNode(9); h->n->n->n = newNode(9); h = addOne(h); while (h != NULL) { cout << h->d; h = h->n; } cout<<endl; return 0; }
# Python3 program to add 1 to a linked list import sys import math # Linked list node class Node: def __init__(self, data): self.data = data self.next = None # Function to create a new node with given data */ def newNode(data): return Node(data) # Function to reverse the linked list */ def reverseList(head): if not head: return curNode = head prevNode = head nextNode = head.next curNode.next = None while(nextNode): curNode = nextNode nextNode = nextNode.next curNode.next = prevNode prevNode = curNode return curNode # Adds one to a linked lists and return the head # node of resultant list def addOne(head): # Reverse linked list and add one to head head = reverseList(head) k = head carry = 0 prev = None head.data += 1 # update carry for next calculation while(head != None) and (head.data > 9 or carry > 0): prev = head head.data += carry carry = head.data // 10 head.data = head.data % 10 head = head.next if carry > 0: prev.next = Node(carry) # Reverse the modified list return reverseList(k) # A utility function to print a linked list def printList(head): if not head: return while(head): print("{}".format(head.data), end="") head = head.next # Driver code if __name__ == '__main__': head = newNode(1) head.next = newNode(9) head.next.next = newNode(9) head.next.next.next = newNode(9) print("List is: ", end="") printList(head) head = addOne(head) print("\nResultant list is: ", end="") printList(head)
Time Complexity: The time complexity of the above solution is linear
Space Complexity: O(1)