dalgorithm
달공의 개발기
dalgorithm
전체 방문자
오늘
어제
  • 분류 전체보기 (170)
    • Back-end (0)
    • Java (11)
    • 자료구조 (7)
    • Network (31)
    • Database (9)
    • Baekjoon Online (24)
    • 클라우드 (6)
    • Android (15)
      • Kotlin (14)
    • AI (27)
      • Machine Learning&Deep Learn.. (27)
    • Web (23)
      • Webhacking (17)
      • WebProgramming (6)
    • 기술면접 (1)
      • JAVA&자료구조 (0)
      • Spring (0)
      • 컴퓨터구조&운영체제 (0)
      • 네트워크 (0)
      • 데이터베이스 (0)
    • CTF 스터디 (15)
    • 대외활동 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • kotlin
  • 머신러닝
  • db
  • python #백준
  • 딥러닝
  • 자료구조
  • 네트워크
  • gcp
  • 코드리뷰
  • 포너블
  • CTF
  • 클라우드
  • 웹해킹
  • 침입탐지
  • 자바
  • 인공지능
  • 데이터베이스
  • java
  • Guacamole
  • cs

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
dalgorithm

달공의 개발기

[자료구조] 스택
자료구조

[자료구조] 스택

2022. 8. 13. 20:29
728x90

스택 (Stack) 이란?

https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Data_stack.svg/300px-Data_stack.svg.png

- 마지막에 들어온 데이터가 먼저나가는 후입선출 자료구조 (LIFO)

- 데이터가 입력된 순서의 역순으로 처리되어야 할 때 사용

 

스택의 연산

● push() : 스택의 가장 윗부분에 추가한다.

● pop() : 스택에서 가장 윗부분에 있는 항목을 제거한다.

● peek() : 스택의 가장 위에 있는 항목을 출력 및 반환한다.

● isEmpty() : 스택이 비어 있을 경우, true를 반환한다.

 

위 메서드 뿐만 아니라, contains(), size(), empty()도 사용 가능하다.

 


스택의 구현

아래와 같은 과정으로 직접 push, pop, peek, contains 등 사용해보며 결과를 확인해 볼 수 있다.

스택의 경우, 괄호 짝을 검사하거나 후위표기법 연산에서 주로 활용할 수 있다.

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Stack stack = new Stack();

        stack.push(1);
        stack.push(2);
    
        System.out.println(stack.pop());
        System.out.println(stack);

        System.out.println(stack.peek());
        System.out.println(stack);

        System.out.println(stack.contains(1));
        System.out.println(stack.size());
        System.out.println(stack.empty());

        stack.clear();
        System.out.println(stack);
        System.out.println(stack.pop());
    }
}

스택의 활용

https://t1.daumcdn.net/cfile/tistory/27594D3B5819C3D703

후위 표기법은 연산자가 피연산자들 뒤에 위치한 경우이다.

컴퓨터에서 수식 계산 순서는 중위 표기식에서 후위표기식으로 걸쳐서 계산한다.

 

1. 수식에서 피연산자가 나오면 무조건 스택에 저장하기

2. 연산자가 나오면 스택에서 피연산자 두 개 꺼내서 연산하고, 결과값을 다시 스택에 저장하기

3. 마지막에는 최종 계산결과만 스택에 남는다.

 

EX 1) 2 2 + = 4

EX 2) 2 2 - =0

 

import java.util.Stack;

public class Practice {
    public static double calculate(String string) {
        Stack<Double> stack = new Stack<Double>();

        for (String str: string.split(" ")) {
            if (str.equals("+")) {
                stack.push(stack.pop() + stack.pop());
            } else if (str.equals("-")) {
                stack.push(- stack.pop() + stack.pop());
            } else if (str.equals("*")) {
                stack.push(stack.pop() * stack.pop());
            } else if (str.equals("/")) {
                stack.push(1 / stack.pop() * stack.pop());
            } else {
                stack.push(Double.parseDouble(str));
            }
        }
        return stack.pop();
    }
 }
728x90

'자료구조' 카테고리의 다른 글

[자료구조] 데크  (0) 2022.08.16
[자료구조] 큐  (0) 2022.08.13
[자료구조] 연결리스트  (0) 2022.08.09
[자료구조] 조합  (0) 2022.08.08
[자료구조] 순열  (0) 2022.07.10
    '자료구조' 카테고리의 다른 글
    • [자료구조] 데크
    • [자료구조] 큐
    • [자료구조] 연결리스트
    • [자료구조] 조합
    dalgorithm
    dalgorithm

    티스토리툴바