c - 将链表附加到另一个链表的末尾

标签 c list merge

我正在尝试将一个列表插入另一个列表的末尾 使用此代码:

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/

相关文章:

c - c中的字符串比较

c - 使用 pthread 创建时钟

python复制嵌套列表

list - Haskell:不使用 (++) 连接列表

r - 合并两个二元变量上的数据框

r - 如何比较两种不同的日期格式?

c - Linux 文件属性检查

c++ - 如何在 C++ 或 C 中进行字符串反转、计算长度?

list - Prolog:如何在两个列表(嵌套 for 循环)之间进行迭代?

git - Beyond Compare - 自动 merge 工作副本中的 "conflicted"文件(如果可能)