문제

I need to make a queue linked list in which the first node always has the smallest value , so it needs to be sorted , I have written this code :

#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();
}

problem is it works only if I add nodes in the above order , for example if I try to add the 3 then 2 then 5 it does not work , what's wrong with the code ? Thank you

도움이 되었습니까?

해결책

Because if you try to add an element that is bigger than everything you have in the list, it will never pass your only condition to add a node: if(newnode->key < curr->key). Try this instead:

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

This way, you go through the linked list until you find the right spot, then add the new node even if you get to the end (curr==NULL).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top