[Java study] 2. Stack

Noah97·2022년 4월 3일
0

JavaStudy

목록 보기
2/2
post-thumbnail

📝Stack이란?

 스택이란 데이터를 일시적으로 저장하기 위해 사용하는 자료구조로, 데이터의 입력과 출력 순서는 후입선출(LIFO, Last In First Out)구조이다. 가장 나중에 넣은 데이터를 가장 먼저 꺼낸다. 스택에 데이터를 넣는 작업을 푸시(push)라 하고, 스택에서 데이터를 꺼내는 작업을 팝(pop)이라고 한다. 테이블에 겹겹이 쌓은 접시처럼 데이터를 넣는 작업도 꺼내는 작업도 위쪽부터 수행한다. 이렇게 푸시와 팝을 하는 위치를 꼭대기(top)이라 하고, 스택의 가장 아랫부분을 바닥(bottom)이라고 한다.

  • 스택의 메서드 종류

1. Push 👇

ex

	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<>(); //int형 스택 선언
		stack.push(42);
		stack.push(43);
		stack.push(44);
		System.out.print(stack);
	}


✅ 순서대로 stack에 push된 것을 볼 수 있다.


2. pop 👆

ex

	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<>();
		stack.push(42);
		stack.push(43);
		stack.push(44);
		stack.pop();
		System.out.print(stack);
	}


✅ pop은 stack에 꼭대기에서 데이터를 제거하고 그 값을 반환하는 메서드이다.


3. peek 🤏

ex

	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<>();
		stack.push(42);
		stack.push(43);
		stack.push(44);
		System.out.print(stack.peek());
	}


✅ 스택의 가장 위에 있는 값을 출력하려면 peek() 메서드를 사용하면 된다. 가장 마지막에 들어간 값이 출력된다.


4. 기타 stack 메서드

ex

	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<>();
		stack.push(42);
		stack.push(43);
		stack.push(44);
		System.out.println(stack.size());
		System.out.println(stack.contains(42));
		System.out.print(stack.empty());
	
	}


✅ size() 메서드는 스택의 크기를 반환하여 출력해주고 contains()는 그 안에 데이터가 있는지 체크하여 true or false를 반환하며 empty()는 스택이 비어있으면 true 아니면 false를 반환해준다.


profile
안녕하세요 반갑습니다😊

0개의 댓글