Skip to content

Commit

Permalink
Create queue_linked.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
PramodhaKasam authored Jan 3, 2025
1 parent eac06f3 commit 50d1067
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions DSA/Stacks & Queues/queue_linked.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Implementation of queue using linked list
#include <bits/stdc++.h>
using namespace std;

class Queue {
public:
int data;
Queue *next;

Queue(int x){
data = x;
next = nullptr;
}
};

void BuildQueue(Queue* &front, Queue* &rear) {
front = rear = nullptr;
}

bool isEmpty(Queue* front) {
return front == nullptr;
}

void Enqueue(Queue* &front, Queue* &rear) {
cout << "Enter a value to enqueue: ";
int val;
cin >> val;
Queue* newQueueNode = new Queue(val);
if (rear == nullptr) {
front = rear = newQueueNode;
} else {
rear->next = newQueueNode;
rear = newQueueNode;
}
}

void Dequeue(Queue* &front, Queue* &rear) {
if (isEmpty(front)) {
cout << "ERROR! Underflow" << endl;
return;
}
cout << "Dequeued element: " << front->data << endl;
Queue* temp = front;
front = front->next;
if (front == nullptr) {
rear = nullptr; // Queue is empty, update rear as well
}
delete temp;
}

int main() {
Queue *front, *rear;
BuildQueue(front, rear);
Enqueue(front, rear);
Enqueue(front, rear);
Enqueue(front, rear);
Enqueue(front, rear);
Enqueue(front, rear);

if (rear != nullptr) {
cout << "Rear element: " << rear->data << endl;
} else {
cout << "Queue is empty." << endl;
}

Dequeue(front, rear);
Dequeue(front, rear);
return 0;
}

0 comments on commit 50d1067

Please sign in to comment.