2021-08-23 11:07:33 +08:00
|
|
|
# STACK
|
|
|
|
|
2021-10-24 15:18:49 +08:00
|
|
|
Stack is an ADT (abstract data type) that acts like a list of objects but there is a difference.
|
2021-08-23 11:07:33 +08:00
|
|
|
|
2021-10-24 15:18:49 +08:00
|
|
|
Stack works on the principle of _LIFO_ (Last In First Out), it means that the last item added to the stack will be the first item to be removed.
|
2021-08-23 11:07:33 +08:00
|
|
|
|
2021-10-24 15:18:49 +08:00
|
|
|
Stack is based on two methods (functions)-
|
2021-08-23 11:07:33 +08:00
|
|
|
|
2021-10-09 00:17:58 +08:00
|
|
|
## push(element)
|
2021-08-23 11:07:33 +08:00
|
|
|
|
2021-10-24 15:18:49 +08:00
|
|
|
It adds "element" to the top of the stack.
|
2021-08-23 11:07:33 +08:00
|
|
|
|
2021-10-24 15:18:49 +08:00
|
|
|
For example: If we have `1, 3, 5` in stack, and we call push(9),
|
2021-08-23 11:07:33 +08:00
|
|
|
|
2021-10-24 15:18:49 +08:00
|
|
|
`9` will be added to last index of stack -> `1, 3, 5 , 9`.
|
2021-08-23 11:07:33 +08:00
|
|
|
|
2021-10-09 00:17:58 +08:00
|
|
|
## peek() or top()
|
|
|
|
|
2021-10-24 15:18:49 +08:00
|
|
|
It returns element at the top of the stack.
|
2021-10-09 00:17:58 +08:00
|
|
|
|
2021-10-24 15:18:49 +08:00
|
|
|
For example: If we have `1, 3, 5` in stack, and we call peek(),
|
2021-10-09 00:17:58 +08:00
|
|
|
|
2021-10-24 15:18:49 +08:00
|
|
|
`5` will be returned (without removing it from the stack).
|
2021-10-09 00:17:58 +08:00
|
|
|
|
|
|
|
## pop()
|
|
|
|
|
2021-10-24 15:18:49 +08:00
|
|
|
It removes the last element (i.e. top of stack) from stack.
|
|
|
|
|
|
|
|
For example: If we have `1, 3, 5 , 9` in stack, and we call pop(),
|
2021-08-23 11:07:33 +08:00
|
|
|
|
|
|
|
the function will return `9` and the stack will change to `1, 3, 5`.
|