简体   繁体   English

单链接列表上的简单插入排序C ++

[英]simple insertion sort on a singly linked list c++

For now, Im not worried about efficiency and I am just learning. 目前,我不担心效率,我只是在学习。 I was wondering if anyone could help me out with learning a simple insertion sort for a singly linked list. 我想知道是否有人可以帮助我学习针对单链接列表的简单插入排序。 This is for my homework so I would like to understand it. 这是我的作业,所以我想理解。 Here is the code: 这是代码:

char c[13];
    r >> c;
    r >> NumberOfInts;

    Node *node = new Node;
    head = node; //start of linked list

    for(int i = 0; i < NumberOfInts; i++) //this reads from the file and works
    {
        r >> node->data;
        cout << node->data << endl;
        node ->next = new Node; //creates a new node
        node = node->next;

        if(_sortRead) //true
        {
            for(int k = 0; k < i; k++)
            {
                         //insertion sort
            }
        }
    }

so far I have it read into an istream so I need to sort it as it gets read in. Node is a struct btw. 到目前为止,我已经将其读入istream,因此我需要对其进行读取时对其进行排序。Node是一个结构btw。 Could anyone help me please? 有人可以帮我吗?

It looks like you're adding one extra node at the end of your list. 您似乎在列表的末尾添加了一个额外的节点。 I suspect you'll wind up with uninitialized data in your last node. 我怀疑您会在最后一个节点中看到未初始化的数据。

Currently you're just adding each new node to the end of the list. 当前,您只是将每个新节点添加到列表的末尾。

Instead of adding each node to the end of the list, you should iterate over the entire list from the front, and find the correct sorted location. 而不是将每个节点添加到列表的末尾,您应该从头开始遍历整个列表,并找到正确的排序位置。 Then insert the node into that sorted location instead of at the end (I believe that's the logic you attempted to implement in your //insertion sort loop. 然后将节点插入排序后的位置,而不是最后插入(我相信这是您尝试在//insertion sort循环中实现的逻辑。

Try build an effective one based on STL. 尝试基于STL构建有效的解决方案。 If you have an ordered list, you could find the good place by lower_bound: 如果您有订单清单,可以通过lower_bound找到合适的地方:

template<class T> std::list<T>::iterator insert( std::list<T> &my_list, const T &value )
{
  return my_list.insert( std::lower_bound( my_list.begin(), my_list.begin(), value ), value );
}

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

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