Question

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

Était-ce utile?

La solution

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).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top