开发者

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 开发者_Python百科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. 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.


Try build an effective one based on STL. If you have an ordered list, you could find the good place by 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 );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜