In: Computer Science
Given C++ Stack Code, Modify the code to work like a Queue.(First in First out)
Stack
#ifndef STACK_H
#define STACK_H
#include "Node.h"
template
class Stack {
private:
Node* top;
public:
// Constructor
Stack() {
top = nullptr;
}
void push(Object ab) {
if (top != nullptr) {
Node* newNode = new Node(ab, *top);
top = newNode;
} else {
Node* newNode = new Node(ab);
top = newNode;
}
}
Object pop() {
if (top != nullptr) {
Node *returnVal = top;
top = top->getNext();
Object returnObject = returnVal->getItem();
delete returnVal;
return returnObject;
} else {
return Object();
}
}
bool isThere(Object a) {
Node* Copy = top;
while (Copy != nullptr) {
if (Copy->getItem() == a) {
return true;
}
Copy = Copy->getNext();
}
return false;
}
};
#endif //STACK_H
QUEUE:
#include "Node.h"
template
class Queue {
private:
Node* front;
Node* rear;
public:
// Constructor
Queue() {
front = nullptr;
rear = nullptr;
}
void push(Object ab) {
if (top != nullptr) {
Node* newNode = new Node(ab, *rear);
rear = newNode;
} else {
Node* newNode = new Node(ab);
front = newNode;
rear = newNode;
}
}
Object pop() {
if (front != nullptr) {
Node *returnVal = front;
front = front->getNext();
Object returnObject = returnVal->getItem();
delete returnVal;
return returnObject;
} else {
return Object();
}
}
bool isThere(Object a) {
Node* Copy = front;
while (Copy != nullptr) {
if (Copy->getItem() == a) {
return true;
}
Copy = Copy->getNext();
}
return false;
}
};