求编程:实现两个长整数相加:要求用链表(单链表或双向链表)实现两个任意数的整数相加。

把设计思想,算法描述,设计技巧也发给我吧,谢谢
2025-04-06 01:04:19
推荐回答(1个)
回答1:

思路不算很难的,首先,设计链表时链表形式为第一个节点为个位,两个链表个位都对其了,就好计算了。其次,相加时产生的进位要记得加入它的上一个高位。

struct Link
{
int data;
struct Link *next;
};

//以逆序的方式创建链表,为了使长整数能从个位开始对其
void CreateLink(struct Link *h)
{
struct Link *p=NULL;
int num=0;
scanf("%d", &num);
while (num<10 && num >= 0 )
{
p = (struct Link *)malloc(sizeof(struct Link));
p->data = num;
p->next = h->next;
h->next = p;
scanf("%d", &num);
}
}

void PrintLink(struct Link *h)
{
struct Link *p=h->next;
int n=0;
while (p)
{
printf("%d",p->data);
p=p->next;
n++;
}
printf("\n这是%d位正数",n);
}
struct Link * TwoLinkAdd(struct Link *h1, struct Link *h2 )
{
struct Link *p1, *p2, *h, *pTemp;
int carry=0;
p1 = h1->next;
p2 = h2->next;
h = (struct Link *)malloc(sizeof(struct Link));
h->next=NULL;
int num=0;
while ( (p1 != NULL) && (p2 != NULL) )
{
num = (p1->data)+(p2->data)+carry;
pTemp = (struct Link *)malloc(sizeof(struct Link));
if (num>=10)
{
pTemp->data = num-10;
carry = 1;
}
else
{
pTemp->data = num;
carry = 0;

}
pTemp->next = h->next;
h->next = pTemp;
p1 = p1->next;
p2 = p2->next;

}
//把多出来的高位数字继续放入新的链表中
struct Link *p=NULL;
if (p1 != NULL)
{
p=p1;
}
if (p2 != NULL)
{
p=p2;
}
while(p != NULL || carry==1)//类似123+897这种情况,最高位还需要进1.
{
pTemp = (struct Link *)malloc(sizeof(struct Link));
pTemp->data = 0;
if (p!=NULL)
{
pTemp->data = p->data;
}

if (carry == 1)
{
pTemp->data = (pTemp->data)+1;
carry = 0;
}
pTemp->next = h->next;
h->next = pTemp;
if (p!=NULL)
{
p = p->next;
}

}
return h;
}
int main(int argc, char **argv)
{
struct Link *head[2];
for (int i=0; i<2; i++)
{
head[i] = (struct Link *)malloc(sizeof(struct Link));
head[i]->next = NULL;
printf("\n请输入大于0,小于10的数,其它数结束:\n");
CreateLink(head[i]);
}
struct Link *h=NULL;
h = TwoLinkAdd(head[0],head[1]);
printf("\nResult:");
PrintLink(h);
//free the pointer.................
return 0;
}