【问题标题】:Sorting a doubly linked list from low to high将双向链表从低到高排序
【发布时间】:2015-10-18 00:32:40
【问题描述】:

我必须在添加数字时对列表进行排序,但我不知道我做错了什么。如果我输入9,5,7,它会打印出7,5,9。所以我假设它正在添加到列表的前面?

这是我目前对列表进行排序的内容:

if (Head == NULL)
{
    Head = newNode;
    newNode->prev = Head;
}
else
{
    Node *curr = Head;
    while (curr->next != NULL && curr->next->data < newNode->data )
    {
        curr->next = curr;
    }

    if (curr == Head)
    {
        Head = newNode;
        curr->prev = newNode;
        newNode->next = curr;
        newNode->prev = Head;
    }
    else if (curr->next != NULL)
    {
        curr->prev->next = newNode;
        newNode->prev = curr;
        newNode->next = curr->next;
        curr->next->prev = newNode;
    }
    else
    {
        newNode->prev = curr;
        curr->next = newNode;
    }
}

【问题讨论】:

  • 所以我假设它添加到列表的前面 -- 为什么假设?调试你的代码看看发生了什么。
  • 你没有正确地将东西插入到列表中,即使它是空的。

标签: c++ linked-list doubly-linked-list


【解决方案1】:

开始纠正这个:

while (curr->next != NULL && curr->next->data < newNode->data )
{
    curr=curr->next;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-12
    • 2020-08-10
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 2014-02-04
    相关资源
    最近更新 更多