cis22c/02-queues/queues_03_pop.cpp
2024-04-28 11:54:46 -07:00

113 lines
2.2 KiB
C++

/**~*~*~*
CIS 22C
Project: Queue of strings (pop)
Written by: Iurii Tatishchev
IDE: CLion
*~*/
#include <iostream>
#include <string>
using namespace std;
class Queue_str {
private:
// Structure for the queue nodes
struct QueueNode {
string value; // Value in the node
QueueNode *next; // Pointer to next node
};
QueueNode *front; // Pointer to the first node
QueueNode *rear; // Pointer to the last node
int length; // Number of nodes in the queue
public:
Queue_str() { front = rear = NULL; length = 0; } //Constructor
~Queue_str(); // Destructor
// Queue operations
bool isEmpty() { return length == 0; }
bool push(string);
string pop();
string peek() { return front->value; }
string peekRear() { return rear->value; }
int getLength() { return length; }
};
/**~*~*
Member function push: inserts the argument into the queue
*~**/
bool Queue_str::push(string item) {
QueueNode *newNode; // Pointer to a new node
// Allocate a new node and store num there.
newNode = new QueueNode;
if (!newNode)
return false;
newNode->value = item;
newNode->next = NULL;
// Update links and counter
if (!front) // front is NULL: empty queue
front = newNode;
else
rear->next = newNode;
rear = newNode;
length++;
return true;
}
/**~*~*~*
Destructor
*~**/
Queue_str::~Queue_str() {
while (front != nullptr) {
QueueNode* nextNode = front->next;
delete front;
front = nextNode;
}
}
/**~*~*~*
Member function dequeue deletes the value at the front
of the queue and returns it.
Assume queue has at least one node
*~**/
string Queue_str::pop() {
string item = front->value;
QueueNode* oldFront = front;
front = front->next;
delete oldFront;
length--;
return item;
}
int main() {
Queue_str que;
string item;
getline(cin, item);
while (item != "#") {
que.push(item);
getline(cin, item);
}
if (que.isEmpty()) {
cout << "Empty Queue!\n";
return 0;
}
while (!que.isEmpty()) {
cout << que.pop() << "\n";
}
return 0;
}