0% found this document useful (0 votes)
10 views1 page

C++ Code

The document contains C++ code that implements a simple queue using a linked list structure. It defines a ListNode class for the nodes of the list and a Queue class with methods to enqueue, dequeue, and print the queue. The queue maintains pointers to the left (front) and right (back) nodes for efficient operations.

Uploaded by

mokshimani123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views1 page

C++ Code

The document contains C++ code that implements a simple queue using a linked list structure. It defines a ListNode class for the nodes of the list and a Queue class with methods to enqueue, dequeue, and print the queue. The queue maintains pointers to the left (front) and right (back) nodes for efficient operations.

Uploaded by

mokshimani123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <iostream>

using std::cout;
using std::endl;

class ListNode {
public:
int val_;
ListNode* next = nullptr;

ListNode(int val) {
val_ = val;
}
};

class Queue {
public:
// Implementing this with dummy nodes would be easier!
ListNode* left = nullptr;
ListNode* right = nullptr;

Queue() {}

void enqueue(int val) {


ListNode* newNode = new ListNode(val);

// Queue is non-empty
if (right != nullptr) {
right->next = newNode;
right = right->next;
}
// Queue
else {
left = right = newNode;
}
}

int dequeue() {
// Queue is empty
if (left == nullptr) {
return -1; // Better to throw an exception
}
// Remove left node and return value
int val = left->val_;
left = left->next;
return val;
}

void print() {
ListNode* curr = left;
while (curr != nullptr) {
cout << curr->val_ << " -> ";
curr = curr->next;
}
cout << endl;
}
};

You might also like