Add 1 to a number represented as a linked list?

CServer Side ProgrammingProgramming

The linked list representation of a number is provided in such a way that the all nodes of the linked list are treated as one digit of the number. The node stores the number such that the first element of the linked list holds the most significant digit of the number, and the last element of the linked list holds the least significant bit of the number. For example, the number 202345 is represented in the linked list as (2->0->2->3->4->5).

And to add one to this linked list represented number we have to check the value of the least significant bit of the list. If it is less than 9 than it's ok otherwise the code will change the next digit and so on.

Now lets see an example to know how to do it, 1999 is represented as (1-> 9-> 9 -> 9) and adding 1 to it should change it to (2->0->0->0)

Input:1999
Output:2000

Explanation

To add 1 to a given number represented as a linked list meaning to follow some steps that are,

  • reversing the linked list: you need to reverse the linked list that this means changing the last digit to the first and the first to the last. 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.

Example

#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;
}
raja
Published on 19-Aug-2019 15:37:03
Advertisements