Stack Algorithm:
The stack can be easily implemented using an Array or a Linked List. Arrays are quick but are limited in size and Linked List requires overhead to allocate, link, unlink, and deallocate, but is not limited in size. Here we will implement Stack using array.
The stack can be easily implemented using an Array or a Linked List. Arrays are quick but are limited in size and Linked List requires overhead to allocate, link, unlink, and deallocate, but is not limited in size. Here we will implement Stack using array.
- In computer science, a stack is an abstract data type that serves as a collection of elements.
- Recursion uses a stack and if you want total control or to avoid some system overhead you can use your own.
- Converting infix to postfix notation
- Do not have a fixed size
- Do not consume a fixed amount of memory
public class Stack { private int arra[]; private int top; private int capacity; //Constructor for initialize Stack Stack(int size) { arra = new int[size]; top = -1; capacity = size; } // Add value in stack public void push(int x) { if (isful()) { System.out.println("Overflow\nProgram Terminated"); System.exit(1); } System.out.println("Insert The Value " + x); arra[++top] = x; } // Remove value from Stack public int pop() { if (isempty()) { System.out.println("Stack is Underflow\nProgram Terminated"); System.exit(1); } System.out.println("Remove The Vallue " + peek()); return arra[--top]; } // Retrive Top Value in Stack public int peek() { if (!isempty()) { return arra[top]; } else { System.exit(1); } return -1; } //Check the Stack full or not. If full then return true public boolean isful() { return top == capacity - 1; } // Check Stack is Empty public boolean isempty() { return top == -1; } // Stack Size public int size() { return top + 1; } public static void main(String[] args) { Stack st = new Stack(5); st.push(1); // Inserting The Element of stack st.push(2); //Inserting The Element of Stack st.push(3); System.out.println("Top element of stack " + st.peek()); st.pop(); // Removing The Element of Stack // Check Stack is Empty or not if (st.isempty()) { System.out.println("Stack is Empty"); } else { System.out.println("Stack is not empty"); } // Stack Size System.out.println("The Stack Size is " + st.size()); } }
Output:
Insert the value 1
Insert the value 2Insert the value 3Top element of stack 3Remove the value 3Stack is not emptyThe Stack size 2
0 Comments