def reverse(queue: MyQueue, k): if queue.size() ==0 or queue.size() < k: return None s = MyStack() for i in range(k): s.push(queue.dequeue()) q1 = MyQueue() for i in range(k): q1.enqueue(s.pop()) while queue.is_empty() is False: q1.enqueue(queue.dequeue()) return q1
def next_greater_element(lst): s = MyStack() res = [-1] * len(lst) for i in range(len(lst) - 1, -1, -1): while not s.is_empty() and s.top() < lst[i]: s.pop() if not s.is_empty(): res[i] = s.top() s.push(lst[i]) return res
def insert(stack:MyStack, value): if(stack.is_empty() or value < stack.top()): stack.push(value) else: temp=stack.pop() insert(stack, value) stack.push(temp)
def evaluate_post_fix(exp): stack = MyStack() try: for c in exp: if c.isdigit(): stack.push(c) else: right = stack.pop() left = stack.pop() result = str(eval(left + c + right)) stack.push(result) return stack.pop() except TypeError: return 'invalid sequence'
class NewQueue: def __init__(self): self.main_stack = MyStack() self.temp_stack = MyStack() def enqueue(self, value): self.main_stack.push(value) return True def dequeue(self): if self.temp_stack.is_empty(): if self.main_stack.is_empty(): return None while self.main_stack.is_empty() is False: self.temp_stack.push(self.main_stack.pop()) temp = self.temp_stack.pop() return temp
def dfs_traversal_helper(g: Graph, source, visited): result = "" q = MyStack() q.push(source) visited[source] = True while q.is_empty() is False: current_node = q.pop() result += str(current_node) temp: Node = g.array[current_node].head_node while temp is not None: if visited[temp.data] is False: q.push(temp.data) visited[temp.data] = True temp = temp.next_element return result, visited
def is_balanced(exp): s = MyStack() for char in exp: if char in ['{', '(', '[']: s.push(char) else: char1 = s.pop() if char == ']' and char1 != '[': return False if char == '}' and char1 != '{': return False if char == ')' and char1 != '(': return False if s.is_empty() is False: return False return True
def sortStack(stack:MyStack): tempStack = MyStack() while stack.is_empty() is False: value = stack.pop() if tempStack.top() is not None and value >= int(tempStack.top()): tempStack.push(value) else: while tempStack.is_empty() is False: stack.push(tempStack.pop()) tempStack.push(value) while tempStack.is_empty() is False: stack.push(tempStack.pop()) return stack
def recursive_sort(stack:MyStack): if stack.is_empty() is False: value = stack.pop() recursive_sort(stack) insert(stack,value)
insert(stack,value) def insert(stack:MyStack, value): if(stack.is_empty() or value < stack.top()): stack.push(value) else: temp=stack.pop() insert(stack, value) stack.push(temp) stack = MyStack() stack.push(2) stack.push(97) stack.push(4) stack.push(42) stack.push(12) stack.push(60) stack.push(23) print(stack.stack_list) recursive_sort(stack) print(stack.stack_list)
def __init__(self): self.main_stack = MyStack() self.temp_stack = MyStack()