def sort_stack(s: Stack): buffer = Stack() while s: cur = s.pop() while buffer and buffer.peek() > cur: s.push(buffer.pop()) buffer.push(cur) while buffer: s.push(buffer.pop())
class SortedStack: def __init__(self): self._main = Stack() self._buffer = Stack() @staticmethod def _move_from_to(s1, s2): while s1: s2.push(s1.pop()) def _to_main(self): self._move_from_to(self._buffer, self._main) def _to_buffer(self): self._move_from_to(self._main, self._buffer) def push(self, val): """ insert 2 _main: [7, 5, 3] """ self._to_buffer() while self._buffer: cur = self._buffer.pop() if val >= cur: self._buffer.push(cur) self._buffer.push(val) break self._main.push(cur) else: self._buffer.push(val) self._to_main() def pop(self): self._to_main() return self._main.pop() def peek(self): self._to_main() return self._main.peek() def __bool__(self): return bool(self._main or self._buffer)
class Queue: def __init__(self): self.back = Stack() self.front = Stack() @staticmethod def _move_from_to(s1: Stack, s2: Stack): while s1: s2.push(s1.pop()) def add(self, val): self._move_from_to(self.front, self.back) self.back.push(val) def remove(self): self._move_from_to(self.back, self.front) return self.front.pop() def peek(self): self._move_from_to(self.back, self.front) return self.front.peek()
def _move_from_to(s1: Stack, s2: Stack): while s1: s2.push(s1.pop())