Mark As Completed Discussion

In order to implement a queue in C++, we can use the concept of linked lists. A queue can be represented as a linked list where each element is a node containing a data value and a pointer to the next node. The front and rear of the queue will be pointers to the first and last nodes, respectively.

Here is an implementation of a queue using linked lists in C++:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4// Node class
5class Node {
6public:
7    int data;
8    Node* next;
9};
10
11// Queue class
12class Queue {
13private:
14    Node* front;
15    Node* rear;
16
17public:
18    // Constructor
19    Queue() {
20        front = nullptr;
21        rear = nullptr;
22    }
23
24    // Check if queue is empty
25    bool isEmpty() {
26        return (front == nullptr);
27    }
28
29    // Enqueue an element
30    void enqueue(int item) {
31        Node* newNode = new Node;
32        newNode->data = item;
33        newNode->next = nullptr;
34
35        if (isEmpty()) {
36            front = rear = newNode;
37        }
38        else {
39            rear->next = newNode;
40            rear = newNode;
41        }
42
43        cout << "Enqueued: " << item << endl;
44    }
45
46    // Dequeue an element
47    void dequeue() {
48        if (isEmpty()) {
49            cout << "Queue is empty" << endl;
50        }
51        else {
52            Node* temp = front;
53            cout << "Dequeued: " << front->data << endl;
54            front = front->next;
55
56            delete temp;
57        }
58    }
59
60    // Get the front element
61    int getFront() {
62        if (isEmpty()) {
63            return -1;
64        }
65        else {
66            return front->data;
67        }
68    }
69};
70
71int main() {
72    // Create a queue object
73    Queue q;
74
75    // Enqueue elements
76    q.enqueue(10);
77    q.enqueue(20);
78    q.enqueue(30);
79
80    // Dequeue elements
81    q.dequeue();
82    q.dequeue();
83
84    // Get the front element
85    int front = q.getFront();
86    cout << "Front element: " << front << endl;
87
88    return 0;
89}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment