Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




STACKS


A 'Stack' can be considered as a container for storing objects. Where the objects are removed and inserted using LIFO (Last In First Out) principle.


i.e. Just consider pile of trays in a cafeteria. You keep on placing the trays on top of each other. Now, the last tray you have placed is on the top and that is the one which has to be removed first.


That is the principle of LIFO(Last In First Out). The last inserted element is removed first.


Inserting an element into the 'Stack' is called 'Pushing'.


And, removal of an item from the 'Stack' is called 'Popping'.


Let us look at the below scenario :


Say there are three books.


java_Collections

Now, you need to place these three books into the 'Stack'. One by One ! By performing Push operation.


  1. So, at first we Push the first book into the 'Stack' :

    Push book1

    java_Collections
  2. Then, we Push the second book into the 'Stack' :

    Push book2

    java_Collections
  3. Next, we Push the third book into the 'Stack':

    Push book2

    java_Collections

Now, all the three books,


java_Collections

are in the 'Stack'.


Next, we will try taking the books out of the stack. And this operation of 'taking out of stack' is called 'Pop'.


Just remember 'book3' would be 'Popped' first.


  1. So, when we run the 'Pop' operation, book3 will be popped first :

    Pop

    java_Collections
  2. Then, once again if we run the 'Pop' operation 'book2' will be popped next :

    Pop

    java_Collections
  3. Finally, when we run the Pop operation, 'book1' will be popped out of the Stack :

    Pop

    java_Collections

Now, that we have seen the basic operations of a Stack. Let us see the supported methods or functions of the Stack.



Methods/Functions used by Stack


Stack mainly uses the below six methods or functions :


  1. new() - Creates a new Stack.
  2. push(stack, element) - Contains two parameters. i.e. 'stack' which is the Stack name and 'element' that is the actual element that will be pushed on top of the stack.
  3. pop(stack) -Contains only one parameter. i.e. 'stack' which is the Stack name. This method removes the top element from the stack.
  4. top(stack) - Contains only one parameter. i.e. 'stack' which is the Stack name. This method returns the top element from the stack without removing it.
  5. size(stack) - Contains only one parameter . i.e. 'stack' which is the Stack name. This method returns the number of elements in the stack.
  6. isEmpty(stack) -Contains only one parameter . i.e. 'stack' which is the Stack name. This method indicates if the stack is empty or not.