전공 지식/자료구조 && 알고리즘
스택으로 큐 구현하기!
큼큼이
2018. 12. 7. 15:07
스택과 큐는 push, pop 하는 위치가 완전히 반대이다.
스택을 이용해서 큐를 구현할 수 있다~
stack<int> st1; stack<int> st2; void push(int num) { st1.push(num); } int pop() { if(st2.empty()) { while(!st1.empty()) { int num = st1.top(); st1.pop(); st2.push(num); } } int ret = st2.top(); st2.pop(); return ret; } int top() { if(st2.empty()) { while(!st1.empty()) { int num = st1.top(); st1.pop(); st2.push(num); } } return st2.top(); }
이제 이 함수를 가지고 push, pop, top 을 하면 큐랑 똑같이 실행된다!