Пример #1
0
class Queue:
    def __init__(self):
        self.stack = Stack()

    def enqueue(self, value):
        self.stack.push(value)
        return True

    def dequeue(self):
        stack1 = Stack()
        stack2 = Stack()

        # 通过两个栈 反转栈 得到第一个
        for _ in range(self.stack.size() - 1):
            stack1.push(self.stack.pop())

        for _ in range(stack1.size()):
            stack2.push(stack1.pop())

        value = self.stack.pop()  # 弹出第一个
        self.stack = stack2
        return value

    def is_empty(self) -> bool:
        return self.stack.size()

    def size(self) -> int:
        return self.stack.size()
Пример #2
0
def reverse_string(str):
    temp = Stack()
    str2 = []
    for i in str:
        temp.push(i)
    print(temp.size())
    i = 0
    while temp.size() > 0:
        str2.append(temp.pop())

    return str2
Пример #3
0
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        # valid parentheses
        # first check empty string
        if len(s) == 0:
            return True
        # using stack for check parentheses
        stack = Stack()  # call for a stack structure
        for i in s:
            if i in ['{', '[', '(']:
                stack.push(i)
            elif i in ['}', ']', ')']:
                if stack.size() == 0:
                    return False
                chFromstack = stack.pop()
                if not ((chFromstack == '{' and i == '}') or
                        (chFromstack == '[' and i == ']') or
                        (chFromstack == '(' and i == ')')):
                    # one of the above conditions
                    return False

        return stack.isEmpty()
Пример #4
0
    def dequeue(self):
        stack1 = Stack()
        stack2 = Stack()

        # 通过两个栈 反转栈 得到第一个
        for _ in range(self.stack.size() - 1):
            stack1.push(self.stack.pop())

        for _ in range(stack1.size()):
            stack2.push(stack1.pop())

        value = self.stack.pop()  # 弹出第一个
        self.stack = stack2
        return value