我创建了两个包含二进制数的链表,并尝试创建一个函数来添加它们并将它们返回到顶部。它接受列表顶部,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;
}
答案 0 :(得分:-1)
通常的解决方案是分离链表操作和添加。你的功能试图做到这两点,这使得它非常不清楚。
我希望方法List add(List const& l1, List const& l2)
。
答案 1 :(得分:-1)
更改
curr1 = n1;
到
*curr1 = *n1;
与curr2类似。