def sort_stack(stack): other_stack = Stack() while not stack.is_empty(): current_v = stack.pop().v flip_count = 0 while not other_stack.is_empty(): last_value = other_stack.peek() if current_v >= last_value: break else: flip_count += 1 other_value = other_stack.pop().v stack.push(other_value) other_stack.push(current_v) for i in range(flip_count): orig_v = stack.pop().v other_stack.push(orig_v) return other_stack
def __init__(self): """ """ self._main_stack = Stack() self._temp_stack = Stack()
class SortedStack(object): """ SortedStack class. """ def __init__(self): """ """ self._main_stack = Stack() self._temp_stack = Stack() def push(self, value): """ :param value: :return: """ done = False if self._main_stack.is_empty(): self._main_stack.push(value) return cur_top = self._main_stack.peek() if value >= cur_top: while not self._main_stack.is_empty(): self._temp_stack.push(self._main_stack.pop()) else: self._main_stack.push(value) return while not self._temp_stack.is_empty(): cur_top = self._temp_stack.pop() if value >= cur_top: self._main_stack.push(value) self._main_stack.push(cur_top) assert self._temp_stack.is_empty(), "Failure, tmp stack not empty." def pop(self): return self._main_stack.pop() def peek(self): return self._main_stack.peek() def is_empty(self): return self._main_stack.is_empty()
from min_stack import Stack def sort_stack(stack): other_stack = Stack() while not stack.is_empty(): current_v = stack.pop().v flip_count = 0 while not other_stack.is_empty(): last_value = other_stack.peek() if current_v >= last_value: break else: flip_count += 1 other_value = other_stack.pop().v stack.push(other_value) other_stack.push(current_v) for i in range(flip_count): orig_v = stack.pop().v other_stack.push(orig_v) return other_stack if __name__ == "__main__": vals = [6, 9, 10, 5, 4, 7, 3, 8, 22, 9] stack = Stack() for v in vals: stack.push(v) print vals print sort_stack(stack)