linked list help?

F

fighterman19

I have 2 singly linked list that contain 1 digit in each node like
this


A [ 1 ]--->[ 2 ]--->[ 3 ]---> NULL

B [ 8 ]---> [ 9 ]--->NULL

I want to add A+B ( 123 + 89) and the sum store in another linked list

sum [ 9 ]---> [ 1 ]---->[ 4 ]---->NULL

all i do are


int carry=0;
do{
int sum =0;

sum= A->value + B->value + carry;
if (sum > 9)
{
carry= sum/10;
sum->value=sum%10;

}
else
{
carry=0;
sum->value=sum%10;
}
// how to move form the first node to second node?

} while (A->next != NULL || B->next !=NULL);

can someone to me how to shift in this one? Thank
 
R

Ron Natalie

// how to move form the first node to second node?

To answer the question you asked,
A = A->next;
B = B->next;
} while (A->next != NULL || B->next !=NULL);

You have bigger logic problems. Your code doesn't handle the
example you gave.

1. Since your lists are different sizes, B->next will be NULL before A->next
is NULL. Your code since it does OR, it will go through the loop with
B set to NULL the last time, invoking undefined behavior trying to do NULL->value.

2. Your code doesn't do what you said it will. Note what it does the first time
through the loop. It add's 1 to 8, next time 2 to 9, ...
 
B

Bill Thompson

jeffc said:
fighterman19 said:
I have 2 singly linked list that contain 1 digit in each node like
this


A [ 1 ]--->[ 2 ]--->[ 3 ]---> NULL

B [ 8 ]---> [ 9 ]--->NULL

I want to add A+B ( 123 + 89) and the sum store in another linked list

sum [ 9 ]---> [ 1 ]---->[ 4 ]---->NULL

You lost me. What is 9, 1, and 4?

It appears the digits are reversed, e.g.
321
+98
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top