如何添加存储在链表中的两个二进制数,并将它们合并到一个链表中?

时间:2016-11-11 07:14:17

标签: c++ linked-list binary

我创建了两个包含二进制数的链表,并尝试创建一个函数来添加它们并将它们返回到顶部。它接受列表顶部,n1(包含第一个二进制数)和n2(包含第二个)。它与普通数组完美配合,但是对于链表,它会产生错误的结果。

Node *BinaryAddition(Node *top, Node *n1, Node *n2)
{
    Node *curr1= (Node*)malloc(sizeof(Node));
    curr1=n1;
    Node *curr2=(Node*)malloc(sizeof(Node));
    curr2=n2;

    int sum = 0;
    int remainder = 0;

    while(curr1!=NULL && curr2!=NULL)
    {
        while((curr1->data != 0 || curr2->data != 0))
        {
            sum=((curr1->data %10) + (curr2->data %10) + remainder)%2;
            top=InsertAtHead(top, sum);
            remainder=((curr1->data%10) + (curr2->data%10) + remainder)/2;
            curr1->data=(curr1->data)/10;
            curr2->data=(curr2->data)/10;
        }

        if(remainder!=0)
        {
            sum=remainder;
            top=InsertAtHead(top,sum);
        }


        curr1=curr1->next;
        curr2=curr2->next;
    }
    return top;
}

2 个答案:

答案 0 :(得分:-1)

通常的解决方案是分离链表操作和添加。你的功能试图做到这两点,这使得它非常不清楚。

我希望方法List add(List const& l1, List const& l2)

答案 1 :(得分:-1)

更改

curr1 = n1;

*curr1 = *n1;

与curr2类似。