알고리즘공부
[자료구조] 스택(Stack)과 큐(Queue)
스마라그드
2020. 2. 25. 22:03
스택(Stack) : 마지막에 들어온 것이 먼저 빠진다.
#include <iostream>
#include <stack>
using namespace std;
int main(void){
stack<int> s;
s.push(7);
s.push(2);
s.push(5);
s.pop();
s.push(6);
s.pop();
while(!s.empty()){
cout << s.top() << ' ';
s.pop();
}
return 0;
}
결과 : 2 7
=> 7 2 5 가 들어온 뒤에 5가 빠지고 6이 들어오고 6이 빠짐 이후 출력시 가장 위의 2가 출력된 뒤 빠지고 다음으로 7이 출력되고 빠짐
큐(Queue) : 먼저 들어온 것이 먼저 빠진다.
#include <iostream>
#include <queue>
using namespace std;
int main(void){
queue<int> q;
q.push(7);
q.push(6);
q.push(4);
q.pop();
q.push(2);
q.pop();
while(!q.empty()){
cout << q.front() << ' ';
q.pop();
}
return 0;
}
결과 : 4 2
=> 7 6 4가 들어온 뒤에 7이 빠지고 2가 들어오고 6이 빠짐, 이후 출력시 가장 앞의 4가 출력된 뒤 빠지고 다음으로 2 가 출력되고 빠짐
STL 라이브러리의 stack과 queue를 사용하여 직접 구현하지 않고 사용하였음..
스택과 큐의 근본적인 차이를 이해하고 사용할 경우를 잘 생각해보자.