Collections
public class Stack {
private int[] arr;
private int top;
private int capacity;
public Stack(int size) {
arr = new int[size];
capacity = size;
top = -1;
}
public void push(int x) {
if (isFull()) {
System.out.println("Stack is full.");
return;
}
arr[++top] = x;
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty.");
return -1;
}
return arr[top--];
}
public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty.");
return -1;
}
return arr[top];
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == capacity - 1;
}
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
System.out.println("Peek: " + stack.peek());
System.out.println("Pop: " + stack.pop());
System.out.println("Pop: " + stack.pop());
System.out.println("Peek: " + stack.peek());
}
}
Stack.main(null);