장성호's
장성호's blog
장성호's
  • 분류 전체보기
    • 알고리즘
      • 백준
      • 이론
    • WEB
      • Spring 인강
      • 네트워크
    • 개인 프로젝트
      • 쇼핑몰 만들기

블로그 메뉴

  • 홈
  • 깃허브
전체 방문자
오늘
어제
반응형
hELLO · Designed By 정상우.
장성호's

장성호's blog

[자료구조] 스택 - Stack
알고리즘/이론

[자료구조] 스택 - Stack

2022. 1. 14. 22:50
반응형

스택이란?

  • LIFO (Last In First Out) 후입선출 특성을 가지는 자료구조
  • 한 쪽 끝에서만 자료를 넣고 뺄 수 있다

[출처] : https://www.programiz.com/dsa/stack

스택의 연산

  • size() : 현재 스택에 들어있는 데이터 원소의 개수를 반환.
  • empty() : 현재 스택이 비어있으면 true, 아닐 경우 false 반환.
  • push(x) : 현재 스택에 데이터 x를 삽입.
  • pop() : 현재 스택의 가장 위에 있는 데이터 원소를 제거.
  • top() : 현재 스택의 가장 위에 있는 데이터 원소를 반환.

 

스택의 구현

#include <iostream>

using namespace std;

const int MAX = 1e5;

class Stack {
private:
  int data[MAX];
  int index;

public:
  Stack();
  int size();
  bool empty();
  void push(int x);
  void pop();
  int top();
};

Stack::Stack() { index = -1; }

int Stack::size() { return index + 1; }

bool Stack::empty() {
  if (index == -1)
    return true;
  else
    return false;
}

void Stack::push(int x) { data[++index] = x; }

void Stack::pop() { index--; }

int Stack::top() { return data[index]; }

int main() {
  Stack s;
  cout << "데이터 입력 : \n";
  s.push(1);
  s.push(2);
  s.push(3);
  s.push(4);
  s.push(5);
  s.push(6);
  cout << "데이터 입력 완료 \n";

  cout << "size() : " << s.size() << "\n";

  cout << "데이터 출력 : [";
  while (!s.empty()) {
    if (s.size() == 1)
      cout << s.top();
    else
      cout << s.top() << " ";
    s.pop();
  }
  cout << "]\n";
}

출력 결과

 

반응형
저작자표시 비영리 변경금지 (새창열림)

'알고리즘 > 이론' 카테고리의 다른 글

[알고리즘] 유클리드 호제법 (Euclidean Algorithm)  (0) 2022.01.18
[자료구조] 덱 - Deque  (0) 2022.01.14
[자료구조] 큐 - Queue  (0) 2022.01.14
[알고리즘] 동적 프로그래밍 (Dynamic Programming)  (0) 2021.12.27
[알고리즘] 탐욕 알고리즘 (Greedy Algorithm)  (0) 2021.12.20
    '알고리즘/이론' 카테고리의 다른 글
    • [자료구조] 덱 - Deque
    • [자료구조] 큐 - Queue
    • [알고리즘] 동적 프로그래밍 (Dynamic Programming)
    • [알고리즘] 탐욕 알고리즘 (Greedy Algorithm)
    장성호's
    장성호's
    장성호's 개발 공부 블로그

    티스토리툴바