我正在尝试将一个列表插入另一个列表的末尾 使用此代码:
typedef struct Element
{
int vKey;
char vInfo[30];
struct Element *pNext;
} tsElement;
typedef struct
{
tsElemento *pFirst;
int vLength;
} tsLDSE;
void Unir(tsLDSE *pListIn, tsLDSE *pListOut)
{
tsElement *pElementOut;
pElementOut = pListOut->pFirst;
while (pElementOut != NULL)
{
pElementOut = pElemenoOut->pNext;
}
pElementOut = pListIn->pFirst;
pListOut->vLength = pListOut->vLength + pListIn->vLength ;
}
我检查了打印地址,pElementoOut实际上是第一个列表的末尾并且指向NULL,然后它接收第二个列表的第一个地址,但是当我打印它时,它只打印第一个列表,我可以不明白为什么。
最佳答案
您的函数Unir
仅将输入列表的长度添加到输出列表的长度。
这个循环:
while (pElementOut != NULL)
{
pElementOut = pElemenoOut->pNext;
}
仅使 pElementOut
为 NULL。
此外,当您编写pElementOut = pListIn->pFirst;
时,您更改的只是局部变量pElementOut
。
您想要做的是:
while (pElementOut->pNext != NULL)
{
pElementOut = pElementOut->pNext;
}
pElementOut->pNext = pListIn->pFirst;
这会将 pListIn 的第一个元素放在 pListOut 最后一个元素的末尾。
另外,在函数的开头添加 NULL 检查!如果你不小心的话,你很容易得到一个 NULL 指针取消引用。
关于c - 将链表附加到另一个链表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33453810/