How to Add 1 To A Number Represented As A LinkedList
HOW TO ADD 1 TO A NUMBER REPRESENTED AS A LINKED LIST
A simple solution using a recursive method
Node *addOne(Node *head)
{
// Your Code here
if(head->data>=10){
Node *newHead=new Node;
newHead->data=1;
head->data=head->data%10;
newHead->next=head;
head=newHead;
return head;
}
if(head->next==0)
{
head->data=head->data+1;
return head;
}
else {
Node* temp=addOne(head->next);
head->data=head->data+temp->data/10;
temp->data=temp->data%10;
}
return head;
}
Comments
Post a Comment