def is_balanced(exp): stack = MyStack() parenthese = {'}': '{', ']': '[', ')': '('} for c in exp: if c in parenthese and not stack.is_empty() \ and stack.top() == parenthese[c]: stack.pop() else: stack.push(c) return stack.is_empty()
def next_greater_element(lst): res = [-1 for x in lst] stack = MyStack() for i in range(len(lst) - 1, -1, -1): while not stack.is_empty() and stack.top() <= lst[i]: stack.pop() if not stack.is_empty(): res[i] = stack.top() stack.push(lst[i]) return res
def next_greater_element(lst): stack = MyStack() res = [None] * len(lst) for i in range(len(lst) - 1, -1, -1): # iterate backwards while not stack.is_empty() and stack.peek() <= lst[i]: stack.pop() if not stack.is_empty(): # use the top element as nge if available res[i] = stack.peek() else: res[i] = -1 stack.push(lst[i]) return res
def sort_stack(stack): temp_stack = MyStack() while not stack.is_empty(): value = stack.pop() # if value is not none and larger, push it at the top of temp_stack if temp_stack.peek() is not None and value >= temp_stack.peek(): temp_stack.push(value) else: while not temp_stack.is_empty(): stack.push(temp_stack.pop()) # place value as the smallest element in temp_stack temp_stack.push(value) # Transfer from temp_stack => stack while not temp_stack.is_empty(): stack.push(temp_stack.pop()) return stack
def sort_stack(stack): sub_stack = MyStack() if stack.is_empty(): return stack while not stack.is_empty(): if sub_stack.is_empty() or stack.top() >= sub_stack.top(): sub_stack.push(stack.pop()) continue val = stack.pop() while not sub_stack.is_empty(): stack.push(sub_stack.pop()) sub_stack.push(val) while not sub_stack.is_empty(): stack.push(sub_stack.pop()) return stack
class MinStack: # Constructor def __init__(self): self.main_stack = MyStack() self.min_stack = MyStack() def pop(self): if self.main_stack.is_empty(): return -1 self.min_stack.pop() return self.main_stack.pop() def push(self, value): self.main_stack.push(value) if self.min_stack.is_empty() or self.min_stack.top() > value: self.min_stack.push(value) else: self.min_stack.push(self.min_stack.top()) def min(self): if not self.min_stack.is_empty(): return self.min_stack.top()
def dfs(g, vertex): num_of_vertices = g.vertices vertices_reached = 0 visited = [False for _ in range(num_of_vertices)] visited[vertex] = True stack = MyStack() stack.push(vertex) while not stack.is_empty(): current_node = stack.pop() temp = g.array[current_node].head_node while temp is not None: if not visited[temp.data]: stack.push(temp.data) visited[temp.data] = True vertices_reached += 1 temp = temp.next_element return vertices_reached + 1
def reverseK(queue, k): if k > queue.size() or k < 0 or queue.is_empty(): return None stack = MyStack() new_q = MyQueue() for i in range(k): v = queue.dequeue() stack.push(v) while not stack.is_empty(): v = stack.pop() new_q.enqueue(v) while not queue.is_empty(): v = queue.dequeue() new_q.enqueue(v) return new_q