Skip to content

Instantly share code, notes, and snippets.

@OscarBastardo
Created September 15, 2020 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OscarBastardo/c468f7e2447737c3b6850599310dd299 to your computer and use it in GitHub Desktop.
Save OscarBastardo/c468f7e2447737c3b6850599310dd299 to your computer and use it in GitHub Desktop.
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