Data structures 给定由两个列表表示的两个数字,编写一个返回sum list的函数

Data structures 给定由两个列表表示的两个数字,编写一个返回sum list的函数,data-structures,linked-list,Data Structures,Linked List,假设您有两个链表5->4(45)和5->4->3(34 5)您必须返回一个结果链表0->9->3(39 0) /*struct Node { int data; Node* next; }; */ Node* addTwoLists(Node* first, Node* second){ int sum = 0, carry = 0; Node *three, *temp, *prev; three = new Node; temp = three; while(first!=NULL

假设您有两个链表5->4(45)5->4->3(34 5)您必须返回一个结果链表0->9->3(39 0)

/*struct Node
{
int data;
Node* next;
}; */

Node*  addTwoLists(Node* first, Node* second){
int sum = 0, carry = 0;
Node *three, *temp, *prev;

three = new Node;
temp = three;

while(first!=NULL || second!=NULL) {
    sum = carry + (first?first->data:0+second?second->data:0);
    carry = sum/10;

    temp->data = sum;
    temp->next = new Node;
    prev = temp;
    temp = temp->next;

    first = first->next;
    second = second->next;
}

    if(carry > 0) {
        temp->data = carry;
        temp->next = NULL;
    }
    else {
        delete temp;
        prev->next = NULL;
    }   
return three;
}


以上代码出现运行时错误(代码转储)。

欢迎使用,因为提供的源代码未编译(prev未定义)。您能提供一个吗?在while循环中,为了只存储一个数字,您应该分配
temp->data=(总和%10)而不是
temp->data=sum。尝试调试代码!亲自查看,并通过编辑您的帖子让人们知道您发现了什么。