【问题标题】:Append linked list to the end of another将链表附加到另一个的末尾
【发布时间】:2015-10-31 16:23:35
【问题描述】:

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

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,然后它接收第二个列表的第一个地址,但是当我打印它时它只打印第一个列表,我可以不知道为什么。

【问题讨论】:

  • 你需要pElemenoOut->pNext = pListIn->pFirst 之前 pElemenoOutNULL
  • 谢谢,它成功了,但我不明白为什么,因为 pElementOut 是 pPrevious->pNext 并且是 null 为什么我不能只是 pElementOut = pListIn->First
  • pElementOut 是与pPrevious->pNext 具有相同值 的局部变量,但pElementOut 不是 pPrevious->pNext
  • 链接,列出所以没有调试,所以 DCV。

标签: c list merge


【解决方案1】:

您的函数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 指针取消引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多