def test_push_one_value(): stack = Stack() stack.push(5) actual = stack.top.value # actual = stack.peek() expected = 5 assert actual == expected
def sort_stack(stack): i, j = 0, int(stack.size/2) size = stack.size while i < j: min, max = find_min_max(stack, i) k = 0 aux = Stack() while k <= size: if k == size - i: aux.push(max) else: value = stack.pop() if value != max: aux.push(value) k += 1 k = 0 stack = Stack() while k <= size: if k == size - i: stack.push(min) else: value = aux.pop() if value != min: stack.push(value) k += 1 i += 1 return stack
def sort_stack2(stack): changes = 0 is_max = True while changes < stack.size - 1 or not is_max: aux = Stack() changes = 0 max_min = stack.pop() while not stack.is_empty(): v = stack.pop() if (is_max and v > max_min) or (not is_max and v < max_min): max_min, v = v, max_min changes += 1 aux.push(v) aux.push(max_min) stack = aux is_max = not is_max return stack
class QueueStack: def __init__(self, value): self.stack = Stack(value) self.r_stack = Stack(value) def add(self, value): self.stack.push(value) self.flip_stack() def remove(self): value = self.r_stack.pop() self.unflip_stack() return value def peek(self): return self.r_stack.peek() def is_empty(self): return self.r_stack.is_empty() def __str__(self): return str(self.stack) + ' - ' + str(self.r_stack) def flip_stack(self): aux = copy.copy(self.stack) # or use a array to pop the two stacks self.r_stack = Stack(aux.pop()) while not aux.is_empty(): self.r_stack.push(aux.pop()) def unflip_stack(self): aux = copy.copy(self.r_stack) self.stack = Stack(aux.pop()) while not aux.is_empty(): self.stack.push(aux.pop())
def stack_vals(): stack = Stack() stack.push(10) stack.push(-2) stack.push('a') return stack