Connecting Tech Pros Worldwide Forums | Help | Site Map

linked list help?

fighterman19
Guest
 
Posts: n/a
#1: Jul 19 '05
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

Ron Natalie
Guest
 
Posts: n/a
#2: Jul 19 '05

re: linked list help?



"fighterman19" <viperboy@hushmail.com> wrote in message news:ufs3mvo4snjfgnvqc046hchb6vh6aopa0n@4ax.com...

[color=blue]
> // how to move form the first node to second node?[/color]

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

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, ...



Bill Thompson
Guest
 
Posts: n/a
#3: Jul 19 '05

re: linked list help?


"jeffc" <nobody@nowhere.com> wrote in message
news:3f622d24_2@news1.prserv.net...[color=blue]
>
> "fighterman19" <viperboy@hushmail.com> wrote in message
> news:ufs3mvo4snjfgnvqc046hchb6vh6aopa0n@4ax.com...[color=green]
> > 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[/color]
>
> You lost me. What is 9, 1, and 4?
>
>[/color]

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



Closed Thread


Similar C / C++ bytes