Created
September 15, 2020 20:02
-
-
Save OscarBastardo/c468f7e2447737c3b6850599310dd299 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def new_stack(size): | |
# our stack will be a list of [list, int] for [contents, head] | |
# so stack[0] is contents | |
# stack[1] is head | |
contents = [0] * size | |
head = 0 | |
return [contents, head] | |
def is_full(stack): | |
# this will not work | |
return stack[1] > len(stack[0]) | |
def is_empty(stack): | |
return stack[1] == 0 | |
def push(stack, x): | |
if is_full(stack): | |
# fail silently, could also raise an error here instead | |
return | |
stack[0][stack[1]] = x | |
stack[1] += 1 | |
def pop(stack): | |
if is_empty(stack): | |
return | |
stack[1] -= 1 | |
return stack[0][stack[1]] | |
if __name__ == "__main__": | |
my_stack = new_stack(5) | |
push(my_stack, 4) | |
push(my_stack, 10) | |
push(my_stack, 3) | |
print(pop(my_stack)) # should print 3 | |
print(pop(my_stack)) # should print 10 | |
push(my_stack, 7) | |
print(pop(my_stack)) # should print 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment