def check_bal_par(par_str): if not len(par_str): return True if len(par_str) % 2 != 0: return False s = Stack() for item in par_str: if s.is_empty(): s.push(item) else: if s.peek() == '(' and item == ')': s.pop() else: s.push(item) return s.is_empty()
def test_pop(self): my_stack = Stack(5) my_stack.push(2) my_stack.push(3) x = my_stack.pop() self.assertEqual(x, 3, "should be 3") self.assertEqual(my_stack.top, 0, "should be 0")
def reverse(string): myStack = Stack(len(string)) for i in string: myStack.push(i) result = "" while not myStack.isEmpty(): result += myStack.pop() return result
def dtob(decimal, base = 2): myStack = Stack() while decimal > 0: myStack.push(decimal % base) decimal //= base # 나머지 result = "" while not myStack.isEmpty(): result += str(myStack.pop()) return result
def parseParenthesis(string): balanced = 1 index = 0 myStack = Stack(len(string)) while (index < len(string)) and (balanced == 1): check = string[index] if check == "(": myStack.push(check) else: if myStack.isEmpty(): balanced = 0 else: myStack.pop() index += 1 if balanced == 1 and myStack.isEmpty(): return True else: return False
def addTwoNumbers(l1, l2): l1_node = l1 stack1 = Stack() while l1_node: stack1.push(l1_node.val) l1_node = l1_node.next l2_node = l2 stack2 = Stack() while l2_node: stack2.push(l2_node.val) l2_node = l2_node.next result = ListNode(None) s = 0 while stack1.size() > 0 and stack2.size() > 0: num1 = stack1.pop() num2 = stack2.pop() node = ListNode(((num1 + num2 + s) % 10)) node.next = result.next result.next = node s = int((num1 + num2 + s) / 10) stack = stack1 if stack1.size() > 0 else stack2 while stack.size() > 0: num = stack.pop() node = ListNode(((num + s) % 10)) node.next = result.next result.next = node s = int((num + s) / 10) if s > 0: node = ListNode(s) node.next = result.next result.next = node return result.next
def is_valid(self, s): array_stack = Stack() str_list = list(s) for index, char in enumerate(str_list): if char == '(' or char == '{' or char == '[': array_stack.push(char) else: if array_stack.is_empty(): return False top_char = array_stack.pop() if char == ')' and top_char != '(': return False if char == ']' and top_char != '[': return False if char == '}' and top_char != '{': return False return array_stack.is_empty()
from stack.Stack import Stack __author__ = 'lijiayan' if __name__ == '__main__': s = Stack() s.push(1) s.push(2) s.push(3) for i in range(s.size()): print(s.pop()) print("栈大小:" + str(s.size()))