728x90
반응형
스택이란?
- LIFO (Last In First Out) 정책
- 데이터를 제한적으로 접근할 수 있는 구조
- 한쪽 끝에서만 자료를 넣거나 뺄 수 있는 구조
- 가장 나중에 쌓은 데이터를 가장 먼저 빼낼 수 있는 데이터 구조
눈으로 어떻게 변하는지 확인해볼 수 있는 웹사이트
https://visualgo.net/en/list?slide=1
Linked List (Single, Doubly), Stack, Queue, Deque - VisuAlgo
VisuAlgo is generously offered at no cost to the global Computer Science community. If you appreciate VisuAlgo, we kindly request that you spread the word about its existence to fellow Computer Science students and instructors. You can share VisuAlgo throu
visualgo.net
>> Stack을 구현해 본 코드
public class Stack<T> {
// stack
private ArrayList<T> stack = new ArrayList<>();
// push
public void push(T item) {
stack.add(item);
}
// pop
public T pop() {
if(stack.isEmpty()) {
return null; // * 스택이 비었으면 null 리턴
} else {
return stack.remove(stack.size() -1); // * 인덱스는 0부터 시작이니깐 -1
}
}
public static void main(String[] args) {
Stack<Object> objectStack = new Stack<>();
objectStack.push(1);
objectStack.push(2);
System.out.println("objectStack = " + objectStack.pop()); // * 어떤 결과가 나올까?
objectStack.push(3);
System.out.println("두번째 꺼내기 = " + objectStack.pop());
System.out.println("세번째 꺼내기 = " + objectStack.pop());
}
}
>> 결과
첫번째 꺼내기 = 2
두번째 꺼내기 = 3
세번째 꺼내기 = 1
1 넣고 2 넣고 3 넣는다
3을 없앤다 2를 없앤다 1을 없앤다
넣은 순의 역순으로 꺼내진다
반응형
'개발자의 공부방 > 알고리즘' 카테고리의 다른 글
알고리즘] 순차 검색(Sequential Search) 알고리즘 (0) | 2023.09.21 |
---|---|
알고리즘] 단어뒤집기 (0) | 2023.08.03 |
알고리즘] 대소문자 변경하기 (0) | 2023.08.03 |
알고리즘] 자료구조, 큐(Queue) (0) | 2021.11.12 |
자바 기초 & 알고리즘] 구구단 (0) | 2019.05.03 |