본문 바로가기
프로그래밍/자료구조 및 알고리즘

스택(Stack)

by 오늘의논리 2023. 3. 7.
728x90

Stack(LIFO Last In First Out) 후입선출

 

되돌리기 기능 

 

1번,2번,3번 차가 막다른길에 도착했다고 하면 3번, 2번, 1번 순으로 나가는것이라고 생각하면 편하다.

 

스택 기능을 구현해보자

#include <iostream>
#include <vector>
#include <stack>
#include <list>
using namespace std;

template<typename T, typename Container = vector<T>>//기본상태 vector
class Stack
{
public:
    void push(const T& value)
    {
        _container.push_back(value);
    }
    void pop()
    {
        _container.pop_back();
    }
    T& top()
    {
        return _container.back();
    }

    bool empty()
    {
        return _container.empty();
    }
    int size()
    {
        return _container.size();
    }

private:
    //vector<T> _container;
    //list<T> _container; // list 도 똑같이 동작함
    Container _container;
};

int main()
{
    Stack<int, list<int>> s;//두번재 인자에 list를 넣어서 동작 할 수 있음

    //삽입
    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);

    // 비엇나?
    while(s.empty() == false)
    { 
        //최상위 원소
        int data = s.top();
    
        //최상위 원소 삭제
        s.pop();

        cout << data << endl;
    }

    int size = s.size();
    return 0;
}

 

728x90

'프로그래밍 > 자료구조 및 알고리즘' 카테고리의 다른 글

이진 탐색  (1) 2023.03.12
힙 트리 이론  (1) 2023.03.12
큐(Queeu)  (0) 2023.03.07
배열, 동적배열, 연결리스트  (0) 2023.03.06
Big-O 표기법  (0) 2023.03.06

댓글