原题为 计算两个均为小于10的链表求和,且和为大于10要进位到下个指针对象里。
以下为代码和调试图
#include <iostream>
using namespace std;
typedef struct Node
{
int data;
struct Node *next;
}Node, *pNode;
int InitList(pNode &pHeader)
{
pHeader = (pNode)malloc(sizeof(Node));
if (nullptr == pHeader)
return -1;
pHeader->next = nullptr;
return 0;
}
void CreateList(pNode &pHeader, int n)
{
pNode p, q = pHeader;
for (int i = 0; i < n; ++i)
{
p = (pNode)malloc(sizeof(Node));
p->data = rand() % 10;
q->next = p;
q = p;
}
q->next = nullptr; //have header; tail insert
}
void PrintList(pNode &pHeader)
{
pNode q = pHeader->next;
while (nullptr != q) {
printf("%d, ", q->data);
q = q->next;
}
printf("\n");
}
void CombineAdd(pNode &La, pNode &Lb, pNode &Lc)
{
pNode pa = La->next;
pNode pb = Lb->next;
pNode p, q = Lc;
int tenLoc = 0;
while (nullptr != pa && nullptr != pb) {
p = (pNode)malloc(sizeof(Node));
p->data = pa->data + pb->data + tenLoc;
if (p->data >= 10)
{
p->data %= 10;
tenLoc = 1;
}
else
{
tenLoc = 0;
}
q->next = p;
q = p;
pa = pa->next;
pb = pb->next;
}
if (nullptr != pa)
q->next = pa;
if (nullptr != pb)
q->next = pb;
}
int main()
{
cout << "Hello World!" << endl;
int m = 15;
int n = 20;
pNode LA, LB, LC;
InitList(LA);
InitList(LB);
InitList(LC);
CreateList(LA, m);
CreateList(LB, n);
PrintList(LA);
PrintList(LB);
CombineAdd(LA, LB, LC);
printf("\n\n");
PrintList(LC);
return 0;
}
测试演示结果
如果有问题请添加QQ-986573837