https://www.acmicpc.net/problem/18258
18258번: 큐 2
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int data) : data(data), next(NULL) {}
};
class Queue {
private:
Node* front;
Node* rear;
int qSize;
public:
Queue() : front(NULL), rear(NULL), qSize(0) {}
~Queue() {
while (!isEmpty()) {
pop();
}
}
bool isEmpty() {
return qSize == 0;
}
void push(int data) {
Node* newNode = new Node(data);
if (isEmpty()) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
qSize++;
}
int pop() {
if (isEmpty()) {
return -1;
}
Node* temp = front;
int ret = temp->data;
front = front->next;
delete temp;
qSize--;
if (isEmpty()) {
rear = NULL;
}
return ret;
}
int getSize() {
return qSize;
}
int getFront() {
if (isEmpty()) {
return -1;
}
return front->data;
}
int getRear() {
if (isEmpty()) {
return -1;
}
return rear->data;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, data;
string cmd;
Queue q;
cin >> n;
while (n--) {
cin >> cmd;
if (cmd == "push") {
cin >> data;
q.push(data);
} else if (cmd == "pop") {
cout << q.pop() << '\n';
} else if (cmd == "size") {
cout << q.getSize() << '\n';
} else if (cmd == "empty") {
cout << q.isEmpty() << '\n';
} else if (cmd == "front") {
cout << q.getFront() << '\n';
} else if (cmd == "back") {
cout << q.getRear() << '\n';
}
}
return 0;
}
'Coding > 백준 온라인 저지 (Baekjoon Online Judge)' 카테고리의 다른 글
백준 온라인 저지(Baekjoon Online Judge) - 25206 : 너의 평점은 (0) | 2023.04.12 |
---|---|
백준 온라인 저지(Baekjoon Online Judge) - 10988 : 팰린드롬인지 확인하기 (0) | 2023.04.12 |
백준 온라인 저지(Baekjoon Online Judge) - 10811 : 바구니 뒤집기 (0) | 2023.04.12 |
백준 온라인 저지(Baekjoon Online Judge) - 10810 : 공 넣기 (0) | 2023.04.12 |
백준 온라인 저지(Baekjoon Online Judge) - 27866 : 문자와 문자열 (0) | 2023.04.12 |