将双向链表从低到高排序

时间:2015-10-18 00:32:40

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

我必须在列表中对其添加数字,但我不知道我做错了什么。如果我输入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;
    }
}

1 个答案:

答案 0 :(得分:0)

开始纠正这个:

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