Update README.md

This commit is contained in:
marina 2023-08-07 17:54:59 -07:00 committed by GitHub
parent f55ce43de3
commit 66a2a3ad3a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,38 +3,47 @@
<br> <br>
* stacks are **last in, first out** structures (LIFO), where the newest element is first one to be removed from the structure. * stacks are **last in, first out** (LIFO) abstract structures, where the newest element is first one to be removed from the structure.
* stacks are useful in certain recursive algorithms, where you can push temp data as you recurse, and remove them from the (memory or data structure) stack as you backtrace.
* a stack support `push` and `pop` at `O(1)`, and they be implmented with arrays or singly linked list.
<br> * stacks are useful in **depth-first search** algorithms, where you can push temp data as you recurse, and remove them from the (memory or data structure) stack as you backtrace.
--- * to keep `find_min()` at `O(1)`, you can keep track of the minimum when pushing and poping:
### some examples in this dir
<br>
#### `stack.py`
<br> <br>
```python ```python
python3 stack.py class Stack:
Testing Stack... def __init__(self):
self.stack = []
self.min = None
Stack: [12, 13, 14, 15, 16, 17, 18, 19, 20] def push(self, val: int) -> None:
Stack size: 9 self.stack.append((val, self.min))
Stack peek: 20 if self.min is not None:
Stack is empty: False self.min = min(self.min, val)
Stack min: 12 else:
self.min = val
Popping... def pop(self) -> None:
20 if self.stack:
19 (val, prior_min) = self.stack.pop()
18 self.min = prior_min
17 return val
16
Stack: [12, 13, 14, 15] return False
```
def top(self) -> int:
if self.stack:
return self.stack[-1][0]
return False
def get_min(self) -> int:
if self.stack:
return self.min
return False
```