/**
* Program Stack (tumpukan) dengan Java
* Author: Riyanto
* Website: kangriyanto.wordpress.com | melonkoding.com
*/
class Stack {
private int[] items;
private int size;
private int top;
public Stack(int size) {
this.size = size;
items = new int[size];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top + 1 == size;
}
public int peek() {
if (top == -1) {
System.out.println("Stack kosong");
return -1;
}
return items[top];
}
public int pop() {
if (top == -1) {
System.out.println("Stack kosong");
return -1;
}
int item = items[top];
top--;
return item;
}
public void push(int item) {
if(top == size - 1) {
System.out.println("Stack penuh");
} else {
top++;
items[top] = item;
}
}
public int size() {
return top + 1;
}
public static void main(String[] args) {
Stack s = new Stack(3);
// tambah item
s.push(1);
s.push(2);
s.push(3);
// apakah penuh
System.out.println("Penuh? : "+ s.isFull());
// lihat item teratas
System.out.println("Teratas: "+ s.peek());
// apakah kosonh
System.out.println("Kosong?: "+ s.isEmpty());
// ambil item teratas
System.out.println("Ambil : "+ s.pop());
System.out.println("Ambil : "+ s.pop());
// apakah kosong
System.out.println("Kosong?: "+ s.isEmpty());
// berapa jumlah item
System.out.println("Ukuran : "+ s.size());
}
}