알고리즘 velog 작성을 다시 시작하기로 하였다. 당분간은 개념을 정립하기 위해 다음과 같은 순서로 글을 작성하려 한다.
1. 개념설명(특징, 사진 등)
2. 사용 방법(코드 설명)
3. 어디에 언제 사용하면 좋은가?
4. 예제
말 그대로 "쌓아놓은 더미" 라는 뜻이다. 후입선출(LIFO) 방식이며 프링글스를 생각하면 쉽다.

import java.util.Stack;
class StackEx {
public static void main(String[] args) {
// Integer형 스택 선언
Stack<Integer> stackInt = new Stack<>();
// String형 스택 선언
Stack<String> stackStr = new Stack<>();
// Boolean형 스택 선언
Stack<Boolean> stackBool = new Stack<>();
}
}
출처: https://ittrue.tistory.com/200 [IT is True:티스토리]
import java.util.Stack;
class StackEx {
public static void main(String[] args) {
// Integer형 스택 선언
Stack<Integer> stackInt = new Stack<>();
// 값 추가 push()
stackInt.push(1);
stackInt.push(2);
stackInt.push(3);
// 1, 2, 3 순으로 값 추가
// 값 제거
stackInt.pop();
stackInt.pop();
stackInt.pop();
// 3, 2, 1 순으로 값 제거
// 값 추가 add()
stackInt.add(1);
stackInt.add(2);
stackInt.add(3);
// 1, 2, 3 순으로 값 추가
// 값 모두 제거
stackInt.clear();
}
}
출처: https://ittrue.tistory.com/200 [IT is True:티스토리]
스택이 비어있는지의 여부를 반환한다. 비어있을 경우 true, 비어있지 않을 경우 false를 반환한다.
import java.util.Stack;
class StackEx {
public static void main(String[] args) {
Stack<Integer> stackInt = new Stack<>();
System.out.println(stackInt.isEmpty());
stackInt.push(1);
System.out.println(stackInt.isEmpty());
}
}
// 출력
true
false
출처: https://ittrue.tistory.com/200 [IT is True:티스토리]
찾고자 하는 값을 스택에서 검색하여 해당 위치를 반환한다. 만약 해당 값이 여러 개일 경우, 마지막 위치를 반환한다. 찾는 값이 없을 경우 -1을 출력한다.
class StackEx {
public static void main(String[] args) {
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:티스토리]