Implement in C++. Create a data structure queue . Write a program that includes the description of the queue

  • 40
Implement in C++. Create a data structure "queue". Write a program that includes the description of the queue and simulates its operation by implementing all the methods mentioned here. The program reads a sequence of commands and, depending on the command, performs a particular operation. After each command execution, the program should output one line. Possible commands for the program: push n add number n to the queue (the value of n is given after the command). The program should output ok. pop remove the first element from the queue. The program should output its value. front the program should output the value.
Алла
70
Решение:

Для начала создадим структуру данных "очередь" (queue) в языке программирования C++. Очередь будет представлять собой последовательность элементов, работающую по принципу FIFO (First In, First Out).

cpp
#include
using namespace std;

struct Node {
int data;
Node* next;
};

class Queue {
private:
Node* front;
Node* rear;

public:
Queue() {
front = nullptr;
rear = nullptr;
}

void push(int n) {
Node* newNode = new Node;
newNode->data = n;
newNode->next = nullptr;

if (front == nullptr) {
front = newNode;
rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}

cout << "ok" << endl;
}

void pop() {
if (front == nullptr) {
cout << "error: queue is empty" << endl;
return;
}

Node* temp = front;
front = front->next;
cout << temp->data << endl;
delete temp;
}

void frontElement() {
if (front == nullptr) {
cout << "error: queue is empty" << endl;
} else {
cout << front->data << endl;
}
}
};

int main() {
Queue q;
string command;
int n;

while (cin >> command) {
if (command == "push") {
cin >> n;
q.push(n);
} else if (command == "pop") {
q.pop();
} else if (command == "front") {
q.frontElement();
}
}

return 0;
}


Этот программный код реализует структуру данных "очередь" и все необходимые для нее методы: добавление элемента (push), удаление элемента (pop) и получение первого элемента (front). Команды выполняются поочередно в зависимости от ввода пользователя.