简体   繁体   English

排序插入双向链表

[英]Sorted Insert Doubly Linked List

I'm trying to make an insertion sort function so that it will sort itself out and then it can display itself in ascending order from top to bottom, and also descending order from bottom to top.我正在尝试进行插入排序 function 以便它会自行排序,然后它可以从上到下以升序显示,也可以从下到上降序显示。 It can display sorted from top to bottom ascending, but not descending from bottom to top.它可以显示从上到下升序排序,但不能从下到上降序显示。 Any help?有什么帮助吗?

void DoublyLinkedList::insert(int v){
    Node* p = new Node;
    p->data = v;
    p->next = nullptr;
    p->prev = nullptr;
    if(top == nullptr || top->data > p->data){
        p->next = top;
        top = p;
    }
    else{
        bottom = top;
        while(bottom->next != nullptr && bottom->next->data < p->data){
            bottom = bottom->next;
        }
        bottom->next->prev = p;
        p->next = bottom->next;
        bottom->next = p;
        p->prev = bottom->prev;
        bottom->prev = p;
    }   
    size++
}

There are two possible reasons for the loop to exit;循环退出有两个可能的原因; either bottom->next is null or bottom->next->data >= p->data . bottom->next是 null 或bottom->next->data >= p->data

The code after the loop assumes that the latter was the reason for exiting, but consider what happen when the item to insert is greater than all the elements in the list.循环之后的代码假定后者是退出的原因,但考虑当要插入的项目大于列表中的所有元素时会发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM