Stacks in Python
A stack is an ordered collection of elements into which items/elements may be added or deleted at one end called the top of the stack. i.e. whenever an element is added it will be added at the top of the stack and whenever an element is deleted it will be deleted from the top of the stack.
Stack follows the policy of LIFO (last in first out) i.e. the element which is added at the end will be the first to be deleted.
The above-given figure Fig:1 represents a stack. it consists of 4 elements/nodes/items A, B, C, and D. Node D represents the top of the stack.
Operations
(i). PUSH (addition of element):
Whenever an element is added in the stack it is always added at the top of the stack. And the newly added node becomes the top of the stack.
Considering the stack represented by Fig 1 whenever an element is added it will be added on top of the node “D” and after addition of element the stack will look like as given below
(ii). POP (Deletion of element)
Whenever an element is deleted from the stack it is always deleted from the top of the stack and after its deletion, the next node in sequence becomes the top of the stack.
Considering the stack represented by Fig 1 whenever an element is deleted it will be the node “D” and after its deletion, the next node i.e. Node “C” will become the top of the stack.
After deletion of an element the stack represented by Fig: 1 will look like as given below.