Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Stack implementation in java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 73
    Comment on it

    Stack is used to store particular type of data. Stack is a memory area where we can store all local variables and parameters used in our functions.

    In Stack we can perform three operations that are :

    Push - to add something in stack with complexity of O(1)

    Pop -  to delete something from stack with complexity of O(1)

    Search -  traverse all items of stack with complexity of O(n)

     

    Array based implementation of stack is easy and efficient :

    public class StackOperations  {
    
        private int top;
        private int storage;
        private int stack[];
    
        public StackOperations(int n, int storage){
            this.top = n;
            this.storage = storage;
            stack = new int[storage];
        }
    
        public void push(int value){
    
            top++;
    
            if (top == -1){
                Log.e(" stack empty"," stack empty");
            }else if (top == storage){
                Log.e(" stack overflow"," stack overflow");
                top--;
            }else{
                stack[top] = value;
            }
    
        }
    
        public void pop(){
    
            if (top == -1){
                Log.e(" stack empty"," stack empty");
            }
    
                top--;
    
        }
    
        public void peek(){
    
            if (top == -1){
                Log.e(" stack empty"," stack empty");
            }else{
                for (int i =0 ; i<=top;i++){
                    Log.e(" stack data"," :: " + stack[i]);
                }
            }
        }
    
    
    }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: