Module 7 - The Stack ADT
Module 7 - The Stack ADT
A stack is a linear data structure that follows the principle of Last In First
Out (LIFO). This means the last element inserted inside the stack is
removed first.
One can think of the stack data structure as the pile of plates on top of
another.
Here, we can:
Put a new plate on top
Remove the top plate
If we want the plate at the bottom, we first have to remove all the
plates on top. This is exactly how the stack data structure works.
// Creating a stack
Stack(int size) {
arr = new int[size];
capacity = size;
top = -1;
}
// Stack implementation in Java Cont’d
// Add elements into stack
public void push(int x) {
if (isFull()) {
System.out.println("OverFlow\nProgram Terminated\n");
System.exit(1);
}
System.out.println("Inserting " + x);
arr[++top] = x;
}
// Stack implementation in Java Cont’d
// Remove element from stack
public int pop() {
if (isEmpty()) {
System.out.println("STACK EMPTY");
System.exit(1);
}
return arr[top--];
}
//Return the size of the stack
public int size() {
return top + 1;
}
// Check if the stack is empty
public Boolean isEmpty() {
return top == -1;
}
// Check if the stack is full
public Boolean isFull() {
return top == capacity - 1;
}
public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.println(arr[i]);
}
}
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();
}
}