Stack: Basic program with all opertations

Stack program with basic operations

 
Java Code
import java.util.*;
    
class Stack{
        
    class Node{
        int data;
        Node next;
        Node(int data){
            this.data = data;
        }
    }

    Node top;
    

    public boolean isEmpty(){
        return top == null;
    }

    public void peek(){ 
        if(isEmpty()){
            System.out.println("Empty stack");
            return;
        }
            
        System.out.println("The top element of the stack is " + top.data);
    }

    public void pop(){
        if(isEmpty()){
            System.out.println("Empty stack");
            return;
        }
        int poppedItem = top.data;
        top = top.next;
        System.out.println("The popped item is "+poppedItem);
    }

    public void push(int data){
        Node node = new Node(data);
        node.next = top;
        top = node;
        System.out.println("The inserted item is " + data);

    }
    
    public void  printStack(){
        if(isEmpty()){
            System.out.println("Empty stack");
            return;
        }

        System.out.print("Stack elements are ");
        List allNodesList = new ArrayList<>();
        Node temp = this.top;
        while (temp != null) {
            allNodesList.add(Integer.toString(temp.data));
            temp = temp.next;
        }
        System.out.println(String.join(" -> ", allNodesList));
    }
    
    
    public static void main(String args[]){

        Stack stack = new Stack();
        stack.push(1);
        stack.push(2);
        stack.pop();
        stack.peek();
        stack.push(3);
        stack.push(4);
        stack.push(5);
        stack.printStack();
        stack.peek();
        stack.pop();
        stack.printStack();
        stack.pop();
        stack.printStack();
        
    }
        
}
Output

The inserted item is 1
The inserted item is 2
The popped item is 2
The top element of the stack is 1
The inserted item is 3
The inserted item is 4
The inserted item is 5
Stack elements are 5 -> 4 -> 3 -> 1
The top element of the stack is 5
The popped item is 5
Stack elements are 4 -> 3 -> 1
The popped item is 4
Stack elements are 3 -> 1

### Complexity Analysis * **Time Complexity**: O(1) for push, pop, and peek. * **Space Complexity**: O(N) where N is the stack capacity.

Share Your Thoughts

Read More....
Implement a stack using queue
Reverse a stack using recursion
Balanced Brackets: Check for balanced brackets in an expression
Browse all Stack articles

Stay Ahead

Only insights that save you time or money. No fluff, ever.

Stay Ahead

Only insights that save you time or money. No fluff.