Пример #1
0
    def conversionToPostOrder(self, inOrdErexpr):
        """
        后序转换
        """
        # 构建运算符优先级字典
        prec = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1, ")": 1}

        if not self.parseChecker(inOrdErexpr):
            raise ValueError

        opStack = Stack()
        postOrderList = list()
        exprList = inOrdErexpr.split()

        for ch in exprList:
            if ch.isdigit():
                postOrderList.append(ch)
            elif ch == "(":
                opStack.push(ch)
            elif ch == ")":
                topOper = opStack.pop()
                while topOper != "(":
                    postOrderList.append(topOper)
                    topOper = opStack.pop()
            else:
                # 比较运算符优先级,如果栈中运算符的优先级>当前运算符, 追加至转换列表中
                while (not opStack.isEmpty()) and (prec[opStack.peek()] >
                                                   prec[ch]):
                    postOrderList.append(opStack.pop())
                opStack.push(ch)
        # 将栈中的运算符追加至转换列表中
        while not opStack.isEmpty():
            postOrderList.append(opStack.pop())
        return "".join(postOrderList)
Пример #2
0
class MyQueue:
    def __init__(self):
        self.new_stack = Stack()
        self.old_stack = Stack()

    def _shift_stacks(self):
        if self.old_stack.is_empty():
            while not self.new_stack.is_empty():
                self.old_stack.push(self.new_stack.pop())

    def add(self, value):
        return self.new_stack.push(value)

    def peek(self):
        if self.is_empty():
            return False
        self._shift_stacks()
        return self.old_stack.peek()

    def remove(self):
        if self.is_empty():
            return False
        self._shift_stacks()
        return self.old_stack.pop()

    def is_empty(self):
        return len(self) == 0

    def __len__(self):
        return len(self.new_stack) + len(self.old_stack)
class MinStack(Stack):
    def __init__(self):
        super().__init__()
        self.minvals = Stack()

    def push(self, value):
        super().push(value)
        if not self.minvals or value <= self.min():
            self.minvals.push(value)

    def pop(self):
        value = super().pop()
        if value == self.min():
            self.minvals.pop()
        return value

    def min(self):
        return self.minvals.peek()