排序队列链表c ++

时间:2014-05-01 17:54:21

标签: c++ data-structures linked-list

我需要创建一个队列链表,其中第一个节点始终具有最小值,因此需要对其进行排序,我已编写此代码:

#include <iostream>
using namespace std;

 struct Node
 {
     int key;
     Node *link;
 };

class qlinkedlist
{
private:
    Node *head;
    Node *tail;
    Node *curr;
    Node *prev;
    int count;

public:
    void Enqueue(int value)
    {
        Node *newnode = new Node;
        newnode -> key = value;
        newnode -> link = NULL;
        if(head==NULL)
        {
            head=tail=newnode;
            count++;
        }
        else if(newnode->key < head->key)
        {
            newnode -> link = head;
            head = newnode;
            count++;

        }
        else
        {
            prev=head;
            curr=head->link;
            while(curr != NULL)
            {
                if(newnode->key < curr->key)
                {
                    prev->link = newnode;
                    newnode->link = curr;
                    count++;
                }
                else
                {
                    prev = curr;
                    curr = curr ->link;
                }
            }
        }
    }


    void Dequeue()
    {
        if(head==NULL)
        {
            cout<< "Queue is empty" << endl;
        }
        else
        {
          curr = head;
          head = head -> link;
          delete curr;
          count--;
        }
    }

    void print()
    {
        curr = head;
        while (curr!=NULL)
        {
            cout << curr -> key << endl;
            curr = curr -> link;
        }
    }

};


void main()
{
    qlinkedlist obj;
    obj.Enqueue(5);
    obj.Enqueue(4);
    obj.Enqueue(3);
    obj.Enqueue(2);
    obj.Enqueue(1);

    obj.print();
}

问题是它是否仅在我按上述顺序添加节点时才有效,例如,如果我尝试添加3然后2然后5它不起作用,代码有什么问题? 谢谢

1 个答案:

答案 0 :(得分:1)

因为如果您尝试添加的元素比列表中的所有元素都大,那么它将永远不会通过您添加节点的唯一条件:if(newnode->key < curr->key)。试试这个:

while(curr != NULL && newnode->key > curr->key)
{
     prev = curr;
     curr = curr ->link;        
}
prev->link = newnode;
newnode->link = curr;
count++;

通过这种方式,您可以浏览链接列表,直到找到正确的位置,然后即使到达目的地也添加新节点(curr == NULL)。