Panda Lee Panda Lee - 18 days ago 5
C++ Question

Why do two pointer pointing to the same link behave differently here?

void fillList(ListNode *&emp,int a[],int n){
ListNode *e=new ListNode(a[0]);
emp=e;
for(int i=1;i<n;++i){
e=e->next;
e=new ListNode(a[i]);
}
}
void showList(ListNode *l){
while(l){
cout<<l->val<<' ';
l=l->next;
}
}


I wrote two functions here, one to fill a empty link with an array, the other to output the link. But when I output the link, it's only the first element from the array. What have I done wrong?
The program is listed as follows. Thanks so much.

#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *p1=l1, *p2=l2, *n1, *n2;
while(p1&&p2){
p1=p1->next;
p2=p2->next;
}
if(p2){n1=l2;n2=l1;}else{n1=l1;n2=l2;}
bool b=0;
while(l1){
if((l1->val+=l2->val)>=10){l1->val-=10;b=1;}
l1=l1->next;
l2=l2->next;
if(b)if(l1)l1->val++;else l1=new ListNode(1);
}
return n1;
}
};
void fillList(ListNode *&emp,int a[],int n){
ListNode *e=new ListNode(a[0]);
emp=e;
for(int i=1;i<n;++i){
e=e->next;
e=new ListNode(a[i]);
}
}
void showList(ListNode *l){
while(l){
cout<<l->val<<' ';
l=l->next;
}
}
int main(){
Solution sol;
ListNode *l1=0,*l2=0;
int a[]={2,4,3},b[]={5,6,4};
fillList(l1,a,3);
fillList(l2,b,3);
//cout<<l1->val<<endl;
showList(l1);
showList(l2);
showList(sol.addTwoNumbers(l1,l2));
}

Answer

First I really want to thank you for your question, very complete.

Actually the problem lies here

for(int i=1;i<n;++i){
    e=e->next;
    e=new ListNode(a[i]);
}

you should change it to the following code to connect all the newly created nodes

for(int i=1;i<n;++i){
    e->next = new ListNode(a[i]);
    e=e->next;
}