본문 바로가기

PS/BOJ

[C++] BOJ (백준) 10828 : 스택

문제

10828번: 스택 (acmicpc.net)

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

코드 1 (std::stack)
#include <iostream>
#include <stack>

using namespace std;

stack<int> st;

void push(int num) {
  st.emplace(num);
}

int pop() {
  if (st.empty()) return -1;

  int res = st.top();
  st.pop();
  return res;
}

int size() {
  return (int) st.size();
}

int empty() {
  return st.empty();
}

int top() {
  if (st.empty()) return -1;

  return st.top();
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);

  int n;
  cin >> n;
  while (n--) {
    string cmd;
    cin >> cmd;
    if (cmd == "push") {
      int num;
      cin >> num;
      push(num);
    } else if (cmd == "pop") {
      cout << pop() << '\n';
    } else if (cmd == "size") {
      cout << size() << '\n';
    } else if (cmd == "empty") {
      cout << empty() << '\n';
    } else if (cmd == "top") {
      cout << top() << '\n';
    }
  }
  return 0;
}

 

설명

stack 헤더의 std::stack을 이용해 손쉽게 풀 수 있다.

 

코드 2 (직접 구현)
#include <iostream>

using namespace std;

struct LinkedList {
  struct Node {
    int data;
    Node *next;

    explicit Node(int data) : data(data), next(nullptr) {}
  };

  Node *head = nullptr;

  [[nodiscard]] bool isEmpty() const {
    return !head;
  }

  void addFront(int data) {
    Node *pNode = new Node(data);
    if (isEmpty()) head = pNode;
    else {
      pNode->next = head;
      head = pNode;
    }
  }

  void deleteFront() {
    head = head->next;
  }
};

struct Stack : LinkedList {
  void push(int num) {
    addFront(num);
  }

  bool empty() {
    return isEmpty();
  }

  int top() {
    if (empty()) return -1;

    return head->data;
  }

  int pop() {
    if (empty()) return -1;

    int res = top();
    deleteFront();
    return res;
  }

  int size() {
    int cnt = 0;
    Node *pNode = head;
    while (pNode) {
      cnt++;
      pNode = pNode->next;
    }
    return cnt;
  }
};

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);

  Stack st;
  int n;
  cin >> n;
  while (n--) {
    string cmd;
    cin >> cmd;
    if (cmd == "push") {
      int num;
      cin >> num;
      st.push(num);
    } else if (cmd == "pop") {
      cout << st.pop() << '\n';
    } else if (cmd == "size") {
      cout << st.size() << '\n';
    } else if (cmd == "empty") {
      cout << st.empty() << '\n';
    } else if (cmd == "top") {
      cout << st.top() << '\n';
    }
  }
  return 0;
}

 

설명

Linked List를 구현한 후 상속하여 Stack을 구현하였다.

'PS > BOJ' 카테고리의 다른 글

[C++] BOJ (백준) 10866 : 덱  (0) 2023.03.05
[C++] BOJ (백준) 10845 : 큐  (0) 2023.03.05
[C++] BOJ (백준) 10816 : 숫자 카드 2  (0) 2023.03.05
[C++] BOJ (백준) 10814 : 나이순 정렬  (0) 2023.03.05
[C++] BOJ (백준) 10773 : 제로  (0) 2023.03.05