Posts

Showing posts with the label Stack

Stack Implementation using Linked List

Image
  // the node of linked list used to implement stack class Node{     int data;     Node next;     Node(int x){         this.data=x;         this.next=null;     } } public class Main {     Node head;       // Function to push an element into stack     // Time Complexity - O(1) , Space Complexity - O(1)     public void push(int data){         Node newNode = new Node(data);               // if linked list is empty         if(head==null){             head=newNode;             return;         }               // else if linked list is not empty, we will add a new node to the start of linked list         newNode.next=head;  ...

Stack implementation and all operations on stack using Array

Image
  Example of stack implementation - back button of the browser _____________________________________ public class Main {     // The Array used to implement stack     int[] arr;     // topOfStack is used to maintain the index of the topmost element present in stack. If not present then it will store -1     int topOfStack;       // constructor     Main(int size){         this.arr = new int[size];         this.topOfStack=-1;     }       // used to initialize the array for stack     // Time Complexity - O(n), Space Complexity - O(n)     public void initializeArray(){         if(topOfStack==-1){             for(int i=0;i<this.arr.length;i++){                 this.arr[i]=Integer.MIN_VALUE;         ...