프로그래밍/C++
자료구조-Queue 간단한 구현
ZenoAhn
2017. 3. 28. 20:38
자료구조 Queue 는 선입 선출 (FIFO) First In First Out의 특징을 가집니다.
배열과 두 개의 index를 이용해서 간단하게 구현 할 수 있습니다.
push
값을 [end]에 삽입, end index 증가
pop
[begin] 출력, begin index 증가
size
end - begin
아래의 코드는 예시 코드입니다.
#include <iostream>#include <string>using namespace std;int main(){std::ios_base::sync_with_stdio();int queue[10000] = {0,};int begin = 0;int end = 0;int n = 0;string command;int value;cin >> n;while (n--){cin >> command;if (command == "push"){cin >> value;queue[end] = value;end++;}else if (command == "pop"){if (begin == end){cout << "-1" << '\n';continue;}cout << queue[begin] << '\n';begin++;}else if (command == "size"){cout << end - begin << '\n';}else if (command == "empty"){if (end - begin == 0){cout << "1" << '\n';}else{cout << "0" << '\n';}}else if (command == "front"){if (end - begin == 0){cout << "-1" << '\n';continue;}cout << queue[begin] << '\n';}else if (command == "back"){if (end - begin == 0){cout << "-1" << '\n';continue;}cout << queue[end - 1] << '\n';}}return 0;}