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.
Now, you need to place these three books into the 'Stack'. One by One ! By performing Push operation.
- So, at first we Push the first book into the 'Stack' :
Push book1
- Then, we Push the second book into the 'Stack' :
Push book2
- Next, we Push the third book into the 'Stack':
Push book2
Now, all the three books,
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.
- So, when we run the 'Pop' operation, book3 will be popped first :
Pop
- Then, once again if we run the 'Pop' operation 'book2' will be popped next :
Pop
- Finally, when we run the Pop operation, 'book1' will be popped out of the Stack :
Pop
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 :
- new() - Creates a new Stack.
- 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.
- pop(stack) -Contains only one parameter. i.e. 'stack' which is the Stack name. This method removes the top element from the stack.
- 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.
- size(stack) - Contains only one parameter . i.e. 'stack' which is the Stack name. This method returns the number of elements in the stack.
- isEmpty(stack) -Contains only one parameter . i.e. 'stack' which is the Stack name. This method indicates if the stack is empty or not.