'what is wrong with the else statement , i am converting string to int to string to linked list
If we have a linked list and pointer to its head. Linked list represent a number. Then add 1 to the number and output the new linked list. For ex 2->6->9 ie 269 should output 270 ie 2->7>0.
My code is running fine when there is no carry, but not otherwise.
I am first taking the number in a string, converting it to a number and converting it back to a string creating the new linked list of the resultant after adding 1 to it.
Node* addOne(Node *head)
{
Node*ptr=head;
while(ptr->next!=NULL){
ptr=ptr->next;
}
if(ptr->data<9){
ptr->data=ptr->data+1;
}
else{
ptr=head;
string s="";
while(ptr!=NULL){
int data=ptr->data;
s=s+to_string(data);
ptr=ptr->next;
}
int x;
x=stoi(s);
x++;
s=to_string(x);
int n=s.length();
Node*head2=(Node*)malloc(sizeof(Node*));
Node*ptr2=head2;
int i=0;
ptr2->data=s[i];
ptr2->next=NULL;
for(i=1;i<n;i++){
Node*temp=(Node*)malloc(sizeof(Node*));
temp->data=s[i];
ptr2->next=temp;
temp->next=NULL;
ptr2=ptr2->next;
}
return head2;
}
return head;
}
Input :
369
Ouput:
515548
Expected Output:
370
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
