이 때 가장 마지막으로 들어온 데이터를 Top, 가장 처음 들어온 데이터를 Bottom이라고 한다
// 배열을 이용한 기본 스택 직접 구현
class CustomStack {
int[] arr;
int top = -1;
CustomStack(int size) {
arr = new int[size];
}
public boolean isEmpty() {
if (this.top == -1) {
return true;
} else {
return false;
}
}
public void push(int data) {
this.top += 1;
if (this.top == arr.length) {
int[] newArr = new int[this.top + 1];
for (int i = arr.length - 1; i >= 0; i--) {
newArr[i] = arr[i];
}
newArr[this.top] = data;
arr = newArr;
} else {
this.arr[this.top] = data;
}
}
public Integer pop() {
if (this.isEmpty()) {
System.out.println("Stack is empty!");
return null;
}
Integer data = this.arr[this.top];
int[] newArr = new int[this.top];
this.top -= 1;
for (int i = 0; i <= top; i++) {
newArr[i] = this.arr[i];
}
arr = newArr;
return data;
}
public Integer peek() {
if (this.isEmpty()) {
System.out.println("Stack is empty!");
return null;
}
return this.arr[this.top];
}
public void printStack() {
for (int i = 0; i < this.top + 1; i++) {
System.out.print(this.arr[i] + " ");
}
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
// Test code
CustomStack myStack = new CustomStack(5);
myStack.isEmpty();
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);
myStack.push(5);
myStack.push(6);
myStack.printStack(); // 1, 2, 3, 4, 5
System.out.println(myStack.peek()); // 5
myStack.printStack(); // 1, 2, 3, 4, 5
System.out.println(myStack.pop()); // 5
myStack.printStack(); // 1, 2, 3
System.out.println(myStack.pop()); // 4
myStack.printStack(); // 1, 2, 3
System.out.println(myStack.pop()); // 3
System.out.println(myStack.pop()); // 2
System.out.println(myStack.pop()); // 1
myStack.printStack();
}
}