Skip to content

Instantly share code, notes, and snippets.

@yokiy
Created July 6, 2014 21:41
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 yokiy/9cb9c81a0b80be6e1b5e to your computer and use it in GitHub Desktop.
Save yokiy/9cb9c81a0b80be6e1b5e to your computer and use it in GitHub Desktop.
cc 3.6
# 3.6 Write a program to sort a stack in ascending order (with biggest items on top). You may use at most one additional stack to hold items, but you may not copy the elements into any other data structure (such as an array).The stack supports the following operations: push, pop, peek, and isEmpty.
from stack import Stack
def sort(stack):
result = Stack()
while stack.isEmpty() is not True:
tmp = stack.pop()
while result.isEmpty() is not True and result.peek() > tmp:
stack.push(result.pop()) #push larger items back to original stack
result.push(tmp)
result.printStack()
#test
test = Stack()
test.push(2)
test.push(8)
test.push(5)
test.push(6)
test.push(4)
print 'the original stack:',
test.printStack()
print 'sorting in ascending order:'
sort(test)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment