单链表c ++上的简单插入排序

时间:2011-04-25 19:20:09

标签: c++ insertion-sort singly-linked-list

现在,我不担心效率,我只是在学习。我想知道是否有人可以帮助我学习单个链接列表的简单插入排序。这是我的作业,所以我想了解它。这是代码:

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
            }
        }
    }

到目前为止,我已将其读入istream,因此我需要在读取时对其进行排序。节点是一个结构btw。有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

您似乎在列表的末尾添加了一个额外的节点。我怀疑你最后一个节点会发现未初始化的数据。

目前,您只是将每个新节点添加到列表的末尾。

您应该从前面迭代整个列表,并找到正确的排序位置,而不是将每个节点添加到列表的末尾。然后将节点插入到已排序的位置而不是最后(我相信这是您尝试在//insertion sort循环中实现的逻辑。

答案 1 :(得分:0)

尝试根据STL构建一个有效的。如果你有一个有序列表,你可以通过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 );
}