给定两个列表所代表的两个数字,编写一个返回总和列表

时间:2017-02-10 17:27:56

标签: data-structures linked-list

假设您有两个链接列表 5-> 4(4 5) 5-> 4-> 3(3 4 5)您必须返回结果链表 0-> 9-> 3(3 9 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;

}

我收到上述代码的运行时错误(Code Dumped)。

0 个答案:

没有答案