#10866번 덱 (c++)

2020. 1. 13. 00:07


 

 

큐와 스택의 장점을 합친 알고리즘. 

앞/뒤에서 삽입이 가능하고 마찬가지로 앞/뒤에서 제거가 가능하다. 

 

#include <iostream>
#include <deque>
#include <algorithm>

using namespace std;

int main(void){
    
    /*
     push_front X: 정수 X를 덱의 앞에 넣는다.
     push_back X: 정수 X를 덱의 뒤에 넣는다.
     pop_front: 덱의 가장 앞에 있는 수를 빼고, 그 수를 출력한다. 만약, 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
     pop_back: 덱의 가장 뒤에 있는 수를 빼고, 그 수를 출력한다. 만약, 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
     size: 덱에 들어있는 정수의 개수를 출력한다.
     empty: 덱이 비어있으면 1을, 아니면 0을 출력한다.
     front: 덱의 가장 앞에 있는 정수를 출력한다. 만약 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
     back: 덱의 가장 뒤에 있는 정수를 출력한다. 만약 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
     */
    
    int num;
    deque<int> dq;
    string order;
    
    cin >> num;
    
    for(int i=0; i<num; ++i)
    {
        
        cin >> order;
        
        if(order == "push_front")
        {
            int n;
            cin >> n;
            dq.push_front(n);
        }
        
        else if(order == "push_back")
        {
            int n;
            cin >> n;
            dq.push_back(n);
        }
        
        else if(order == "pop_front")
        {
            if(dq.empty())
            {
                cout << "-1" << endl;
            }
            
            else
            {
                cout << dq.front() << endl;
                dq.pop_front();
            }
        }
        
        else if(order =="pop_back")
        {
            if(dq.empty())
            {
                cout << "-1" <<endl;
            }
            
            else
            {
                cout << dq.back() <<endl;
                dq.pop_back();
            }
        }
        else if(order == "size")
        {
            cout << dq.size() <<endl;
        }
        
        else if(order == "empty")
        {
            if(dq.empty())
            {
                cout << 1 <<endl;
            }
            else
            {
                cout << 0 <<endl;
            }
        }
        
        else if(order == "front")
        {
            if(dq.empty())
            {
                cout << "-1" <<endl;
            }
            else
            {
                cout << dq.front() <<endl;
            }
        }
        
        else if(order == "back")
        {
            if(dq.empty())
            {
                cout << "-1" <<endl;
            }
            else
            {
                cout << dq.back() <<endl;
            }
        }
    }
    
    return 0;
}