Skip to content

Instantly share code, notes, and snippets.

@ttowncompiled
Last active May 21, 2017 06:50
Show Gist options
  • Save ttowncompiled/09d5b7c514f0c4724cd4d450c58cfa9b to your computer and use it in GitHub Desktop.
Save ttowncompiled/09d5b7c514f0c4724cd4d450c58cfa9b to your computer and use it in GitHub Desktop.
A Queue implemented with 2 stacks to use for HackerRank problems.
###
# Python 3
# Q = [ [], [] ]
###
def size(Q):
return len(Q[0]) + len(Q[1])
def is_empty(Q):
return (len(Q[0]) + len(Q[1])) == 0
def peek(Q):
if len(Q[1]) == 0:
while len(Q[0]) > 0:
Q[1].append(Q[0].pop())
return Q[1][-1] if len(Q[1]) > 0 else None
def enqueue(Q, x):
Q[0].append(x)
def dequeue(Q):
if len(Q[1]) == 0:
while len(Q[0]) > 0:
Q[1].append(Q[0].pop())
return Q[1].pop() if len(Q[1]) > 0 else None
# The End
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment