class CustomStack(Stack): def __init__(self): super().__init__() self.min_stack = Stack() def push(self, value): # Keep track of the min value if self.min_stack.is_empty() or self.min_stack.peek() >= value: self.min_stack.push(value) super().push(value) def pop(self): value = super().pop() if value == self.min_stack.peek(): self.min_stack.pop() return value def get_minimum(self): if not self.min_stack.is_empty(): return self.min_stack.peek()
def consolidate(self): """ Restructure the tree back to a binomial tree """ trees_by_rank = {} tree_stack = Stack() for tree in self.trees: tree_stack.push(tree) # Iterate over the trees and merge trees of the same rank while not tree_stack.is_empty(): tree = tree_stack.pop() if tree is None: continue if tree.rank in trees_by_rank: existing_tree = trees_by_rank[tree.rank] del trees_by_rank[tree.rank] tree_stack.push(tree.merge_min(existing_tree)) else: trees_by_rank[tree.rank] = tree # Build a new tree list and find the new min node new_trees = trees_by_rank.values() self.trees = LinkedList() self.min_tree = None for new_tree in new_trees: self.trees.append(new_tree) if self.min_tree is None or self.min_tree.value.value > new_tree.value: self.min_tree = self.trees.get_tail_node()
class CustomQueue(): def __init__(self): self.enqueue_stack = Stack() self.dequeue_stack = Stack() def enqueue(self, value): while not self.dequeue_stack.is_empty(): self.enqueue_stack.push(self.dequeue_stack.pop()) return self.enqueue_stack.push(value) def dequeue(self): while not self.enqueue_stack.is_empty(): self.dequeue_stack.push(self.enqueue_stack.pop()) return self.dequeue_stack.pop() def is_empty(self): return not self.enqueue_stack.size() and not self.dequeue_stack.size()
def sort_stack(stack: Stack): extra_stack = Stack() while not stack.is_empty(): element = stack.pop() elements_transfered = 0 while not extra_stack.is_empty() and extra_stack.peek() > element: elements_transfered += 1 stack.push(extra_stack.pop()) extra_stack.push(element) for _ in range(elements_transfered): extra_stack.push(stack.pop()) while not extra_stack.is_empty(): stack.push(extra_stack.pop())