Queue using Linked List

 avatar
itsLu
c_cpp
2 months ago
2.0 kB
3
Indexable
Never
//constructor, isEmpty, enqueue, dequeue, getNumberOfElements, displayData, deleteQueue, destructor
#include <iostream>
using namespace std;

struct node
{
    int data;
    node *next;
};

class LinkedQueue
{
    node *frnt, *rear;
public:
    LinkedQueue()
    {
       frnt = rear = NULL;
    }
    bool isEmpty()
    {
        return frnt == NULL;
    }
    void enqueue (int data)
    {
        node *item = new node;
        item->data = data;
        item->next = NULL;
        if (isEmpty())
            frnt = rear = item;
        else
        {
            rear->next = item;
            rear = item;
        }
    }
    int dequeue()
    {
        if (isEmpty())
        {
            cout << "\nQueue is empty!\n";
            return -1;
        }
        node *temp = frnt;
        int tempData = temp->data;
        frnt = frnt->next;
        delete temp;
        return tempData;
    }
    int getNumberOfElements()
    {
        int counter;
        node *temp;
        for (temp = frnt ; temp != NULL ; temp = temp->next)
            counter++;
        return counter;
    }
    void displayQueue()
    {
        node *temp;
        for (temp = frnt ; temp != NULL; temp = temp->next)
            cout << temp->data << "\t";
    }
    void deleteQueue()
    {
        node *temp;
        while (frnt != NULL)
        {
            temp = frnt;
            frnt = frnt->next;
            delete temp;
        }
    }
    ~LinkedQueue()
    {
        deleteQueue();
        cout << "\nQueue is deleted!";
    }
};

int main()
{
    LinkedQueue queue1;
    for (int k = 0 ; k <= 10 ; k+=2)
        queue1.enqueue(k);
    queue1.displayQueue();
    cout << endl << queue1.getNumberOfElements() << endl;
    cout << queue1.dequeue() << "\t" << queue1.dequeue() << endl;
    queue1.displayQueue();
    cout << endl << queue1.getNumberOfElements() << endl;
}
Leave a Comment