스택에 관련된 문제를 풀다가 개념 정리가 필요할 것 같아서 정리하게 됐다
2023.07.11 - [➜ 코딩 테스트/백준] - 백준 - (25556) 포스택
백준 - (25556)포스택
1. 길이가 N인 순열과 4개의 비어 있는 스택이 있다. 2. 순열의 원소들을 앞에서부터 순서대로 네 개의 스택 중 하나에 삽입한다. 3. 순열의 모든 원소를 스택에 삽입했다면, 원하는 스택에서 수를
mangseok.tistory.com
스택(Stack)
자료 구조 중 하나로, LIFO (Last In First Out)의 특징을 가지고 있다. 이는 스택의 가장 마지막에 들어간 요소가 가장 먼저 나오게 되는 구조를 의미한다.
스택의 예시 그림을 그려 봤는데 이런 식으로 하나씩 쌓아가고 맨 위에 있는 요소가 먼저 나가게 되는 작업이다.
스택에 데이터를 추가하는 동작은 push
스택에 데이터를 빼는 동작은 pop이라고 한다
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
System.out.println(stack); // 출력: [1, 2]
push 예시
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
int poppedItem = stack.pop();
System.out.println(poppedItem); // 출력: 2
pop 예시
이런 식으로 마지막에 푸시된 값만 출력이 된다
Stack 관련 메서드
Stack<Integer> stack = new Stack<>();
//요소 추가
stack.push(1);
//요소 꺼내기
stack.pop();
//스택 비우기
stack.clear();
//스택 크기 체그
stack.size();
//스택이 비어있는지 확인
stack.empty();
//스택 요소 존재 확인
stack.contains(1);
//스택 최상단 요소 확인
stack.peek();
//스택 데이터 추가
stack.add(1);
//찾고있는 데이터가 있는 인덱스 위치 반환
stack.search(1);
//스택의 주어진 인덱스 위체이 있는 요소 반환
stack.elementAt(1);
//스택의 현재 용량을 반환
stack.capacity();
//스택의 모든 요소 제거
stack.clear();
//스택의 모든 요소들을 배열로 변환
stack.toArray();
- peek()
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
int topItem = stack.peek();
System.out.println(topItem); // 출력: 2
- isEmpty()
Stack<Integer> stack = new Stack<>();
System.out.println(stack.isEmpty()); // 출력: true
stack.push(1);
System.out.println(stack.isEmpty()); // 출력: false
- search(Object o)
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
int position = stack.search(1);
System.out.println(position); // 출력: 2
- element(int index)
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
int element = stack.elementAt(1);
System.out.println(element); // 출력: 2
- capacity()
Stack<Integer> stack = new Stack<>();
System.out.println(stack.capacity()); //기본 생성 시 용량 10
- clear()
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.clear();
System.out.println(stack.size()); // 출력: 0
- size()
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
System.out.println(stack.size()); // 출력: 2
- contains(Object o)
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
boolean contains = stack.contains(1);
System.out.println(contains); // 출력: true
- search(Object o)
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
System.out.println(stack.search(1)); // 출력: 2
System.out.println(stack.search(3)); // 출력: -1 객체가 스택에 없으면 -1 반환
- toArray()
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
Object[] array = stack.toArray();
System.out.println(Arrays.toString(array)); // 출력: [1, 2]