|
| 1 | +# Stack |
| 2 | +Stack is a data structure that restricts |
| 3 | +the order in which operations can be performed. |
| 4 | + |
| 5 | + |
| 6 | + |
| 7 | +*Source: Programiz* |
| 8 | + |
| 9 | +### Operation Orders |
| 10 | + |
| 11 | +Stack follows a LIFO, last in first out order. |
| 12 | +This means the most recent element |
| 13 | +added to the stack is the one operations are conducted on first. |
| 14 | + |
| 15 | +A [queue](../queue/README.md) conducts operations in the opposite order. |
| 16 | + |
| 17 | +## Analysis |
| 18 | + |
| 19 | +As a stack only interacts with the most recent element regardless of operation, |
| 20 | +it keeps the pointer of the most recent element at hand, which is constantly updated as more |
| 21 | +elements are removed / added. This allows stack operations to only incur a *O(1)* time complexity. |
| 22 | + |
| 23 | +## Notes |
| 24 | + |
| 25 | +### Stack vs Queues |
| 26 | + |
| 27 | +Stack and queues only differ in terms of operation order, you should aim to use a stack when |
| 28 | +you want the most recent elements to be operated on. |
| 29 | +Some situations where a stack would work well include build redo / undo systems and backtracking problems. |
| 30 | + |
| 31 | +On the other hand, a queue allows you to operate on elements that enter first. Some situations where |
| 32 | +this would be useful include Breadth First Search algorithms and task / resource allocation systems. |
| 33 | + |
| 34 | +### Arrays vs Linked List |
| 35 | +It is worth noting that stacks can be implemented with either a array or with a [linked list](../linkedList/README.md). |
| 36 | +In the context of ordered operations, the lookup is only restricted to the first element. |
| 37 | + |
| 38 | +Hence, there is not much advantage in using a array, which only has a better lookup speed (*O(1)* time complexity) |
| 39 | +to implement a stack. Especially when using a linked list to construct your stack |
| 40 | +would allow you to grow or shrink the stack as you wish. |
0 commit comments