Java Stack 클래스 메서드 사용법

어디든 배우자·2024년 1월 22일

스택이란

데이터를 순서대로 쌓는 자료구조.
가장 나중에 들어온 데이터가 가장 먼저 빠져나가는 구조이다.
스택은 데이터가 입력된 순서대로 처리되는 것이 아닌,
가장 나중에 들어온 데이터를 먼저 처리할 때 사용함.

특징

데이터를 하나씩만 넣고 뺄 수 있다.

선언

Integer, String, Boolean 등등 다양하게 선언 가능하다.

Stack<Integer> stackInt = new Stack<>();
Stack<String> stackInt = new Stack<>();

값 추가 및 제거

add(), push()를 통해 값을 하나씩 추가 가능. 추가된 값을 빼내고 싶으면 pop() 메서드 사용.
또한, 모든 내용을 제거하고 싶으면 clear() 메소드 사용
pop() 메서드를 사용하면, 스택의 값이 제거됨과 동시에 해당 값을 반환.
하지만 clear() 메서드는 반환 값이 없다.

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

stackInt.push(1);
stackInt.push(2);
stackInt.push(3);
// 1, 2, 3 순으로 값 추가

stackInt.pop();
stackInt.pop();
stackInt.pop();
// 3, 2, 1 순으로 값 제거

stackInt.add(1);
stackInt.add(2);
stackInt.add(3);
// 1, 2, 3 순으로 값 추가

// 값 모두 제거
stackInt.clear();

스택 클래스 메서드

peak()

스택의 마지막 요소를 반환하며, 스택에는 변화를 주지 않음.
만약 스택이 비어있으면 NoSuchElementException 예외 발생.

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

stackInt.push(1);
stackInt.push(2);
stackInt.push(3);

System.out.println(stackInt.peek());
//출력
3

pop()

스택의 마지막 요소를 제거하고, 해당 값을 반환.

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

stackInt.push(1);
stackInt.push(2);
stackInt.push(3);

System.out.println(stackInt.pop());
System.out.println(stackInt);
//출력
3
[1,2]

empty()

스택이 비어있는지의 여부 반환, 비어있으면 true, 그렇지 않으면 false

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

System.out.println(stackInt.isEmpty());
stackInt.push(1);
System.out.println(stackInt.isEmpty());
//출력
true
false

메서드의 인자를 스택에서 검색하여 해당 위치를 반환. 만약 해당 인자가 중복이라면 마지막 위치를 반환. 찾는 값이 없다면 -1 반환.

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

stackInt.push(1);
stackInt.push(2);
stackInt.push(3);
stackInt.push(1);
// [1, 2, 3, 1]

System.out.println(stackInt.search(2));
System.out.println(stackInt.search(1));
System.out.println(stackInt.search(4));
//출력
3
1
-1
출처: https://ittrue.tistory.com/200 [IT is True:티스토리]
profile
다 흡수하기.

0개의 댓글