자료구조-스택 문제

Seok·2022년 1월 24일
0
post-thumbnail

문제풀이

자료구조 중 LIFO구조인 스택의 기본적인 동작들을 구현하는 문제로 Stack 클래스를 사용하면 쉽게 풀 수 있는 문제였다.

Stack이란?

자료구조 중 하나인 Stack은 상자에 물건을 쌓아 올리듯이 데이터를 쌓는 자료 구조라고 할 수 있다.

Stack의 특징

  • 먼저 들어간 자료가 나중에 나온다. LIFO(Last In First Out) 구조
  • 시스템 해킹에서 버퍼오버플로우 취약점을 이용한 공격을 할 때 스택 메모리의 영역에서 한다.
  • 인터럽트 처리, 수식의 계산, 서브루틴의 복귀 번지 저장 등에 쓰인다.
  • 그래프의 깊이 우선 탐색(DFS)에서 사용된다.
  • 재귀함수를 호출할 때 사용된다.

Stack클래스의 사용법

Stack<Integer> s = new Stack<>();

s.push(i); // 스택의 값 넣기
s.pop(); // 스택의 가장 위의 값 빼고 출력하기
s.size(); // 스택의 크기
s.peek(); // 스택의 가장 위의 값 조회

소스 코드

package data_structure;

import java.util.*;

public class stack1 {
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Stack<Integer> stack = new Stack<>();
		Scanner in = new Scanner(System.in);
		
		int n = in.nextInt();
		
		for(int i = 0; i<n; i++) {
			String str = in.next();
			
			switch(str) {
			
			case "push":
				int item = in.nextInt();
				stack.push(item);
				break;
			case "pop":
				System.out.println(stack.isEmpty() ? -1 : stack.pop());
				break;
			case "size":
				System.out.println(stack.size());
				break;
			case "empty":
				System.out.println(stack.isEmpty() ? 1 : 0);
				break;
			case "top":
				System.out.println(stack.isEmpty() ? -1 : stack.peek());
				break;
			}
		}
	}
}
profile
네이티브 앱개발에 관심많은 주니어 개발자

0개의 댓글