후입선출(LIFO, Last In First Out) 방식으로 동작하는 자료구조
쉽게 말해서 종이를 쌓아올리는 것과 비슷하다고 한다.
1종이 > 2종이 > 3종이 > 4종이 순서로 쌓아올리면
위에서부터 종이를 들어올릴 때에는
4종이 > 3종이 > 2종이 > 1종이 순서가 되고,
이것이 후입선출이라는 단어인 것 같다.
push() : 스택의 맨 위(top)에 데이터를 추가
pop() : 스택의 맨 위(top) 데이터를 제거
peek() : 스택의 맨 위(top) 데이터를 제거하지 않고 확인
isEmpty() : 스택이 비어있는지 확인
.
.
.
Input과 Output이 한 방향인 일방통행
스택이 왜 사용되는 걸까? 바로 전에 배운 LinkedList도 순서가 정해지는 로직이었는데...
이 이후에 구현까지 들어보면 알 수 있을 것 같기도 하다.
package Stack;
public class Main {
public static class Stack {
private int[] data;
private int top;
private int size;
public Stack() {
this.size = 0;
this.data = new int[10];
top = -1;
}
public void push(int data) {
if (isFull()) {
System.out.println("스택이 가득 찼습니다.");
return;
}
this.data[++top] = data;
this.size++;
}
public void pop() {
if (isEmpty()) {
System.out.println("전체 스택이 비어있습니다.");
return;
}
this.top--;
this.size--;
}
public int peak() {
if (isEmpty()) {
System.out.println("전체 스택이 비어있습니다.");
return -1;
}
return this.data[top];
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == data.length -1;
}
public void printStack() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i <= top; i++)
sb.append(data[i]).append(" ");
System.out.println(sb.toString());
}
}
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
stack.printStack();
stack.pop();
stack.printStack();
System.out.println(stack.isEmpty());
stack.pop();
stack.pop();
stack.pop();
stack.push(5);
System.out.println(stack.peak());
for (int i = 1; i < 10; i++)
stack.push(i);
stack.printStack();
System.out.println(stack.isFull());
stack.push(100);
}
}