Skip to content

Instantly share code, notes, and snippets.

@z1nc0r3
Created August 27, 2022 12:12
Show Gist options
  • Save z1nc0r3/c2ea02d4e39cca4803f8e8c0de1f8a03 to your computer and use it in GitHub Desktop.
Save z1nc0r3/c2ea02d4e39cca4803f8e8c0de1f8a03 to your computer and use it in GitHub Desktop.
Stack using integer Array
public class Stack {
private int[] stack;
private int arrayLength;
private int current = -1;
public Stack(int arrayLength) {
this.arrayLength = arrayLength;
stack = new int[arrayLength];
}
public void push(int value) {
if (!isFull()) {
stack[++current] = value;
} else {
System.out.println("stack overflow");
}
}
public void pop() {
System.out.println(!isEmpty() ? stack[current--] : "stack underflow");
}
public void peek() {
System.out.println(!isEmpty() ? stack[current] : "stack is empty");
}
public void print() {
for (int x : stack) {
System.out.print(x + " ");
}
}
public boolean isFull() {
return (current == arrayLength-1);
}
public boolean isEmpty() {
return (current == -1);
}
public static void main(String[] args) {
Stack stack = new Stack(7);
stack.pop();
stack.peek();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.push(60);
stack.push(70);
stack.peek();
stack.print();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment