Kod dibawah adalah dalam Java.
public class Stack {
// PROPERTIES
int[] stack;
int maxStack = 5;
int top;
// CONSTRUCTOR
public Stack() {
this.top = -1;
this.stack = new int[maxStack];
// {0, 0, 0, 0, 0}
// Setting the default value
for (int i = 0; i < maxStack; i++) {
this.stack[i] = -999;
}
// -999 = position adalah kosong
}
// METHOD
// isEmpty()
public boolean isEmpty() {
if (this.top == -1) {
return true;
} else {
return false;
}
}
// isFull()
public boolean isFull() {
if (this.top + 1 == this.maxStack) {
return true;
} else {
return false;
}
}
// display()
public void display() {
System.out.print("Elemen di dalam stack: ");
for (int i = 0; i < stack.length; i++) {
if (this.stack[i] != -999) {
System.out.print(this.stack[i] + " ");
}
}
System.out.println();
}
// push()
public void push(int newItem) {
if (!isFull()) {
this.top++;
this.stack[this.top] = newItem;
}
}
// pop()
public int pop() {
int removedItem = -999; // Nilai default
if (!isEmpty()) {
removedItem = this.stack[this.top];
this.stack[this.top] = -999;
this.top--;
}
return removedItem;
}
// peek()
public int peek() {
int peekedItem = -999; // Nilai default
if (!isEmpty()) {
peekedItem = this.stack[this.top];
}
return peekedItem;
}
}