【python数据结构】栈&队列专题练习--选题来自Github大神CyC2018

按照CyC2018 (Github star 超过99k, 详情请见https://github.com/CyC2018/CS-Notes/blob/master/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E6%A0%88%E5%92%8C%E9%98%9F%E5%88%97.md)总结的练习【python版】。

废话不多说,上菜~

元素每经过一个栈,出栈的顺序就会被反转,因此连续经过两个栈,就可达到队列先进先出的目的。2

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.A = []
        self.B = []
        
    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.A.append(x)
        
    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        if len(self.B)==0 and len(self.A)==0:
            return True
        else:
            return False

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if self.empty():
            return
        if len(self.B) == 0:
            while len(self.A) != 0:
                self.B.append(self.A.pop())
            return self.B.pop()
        else:
            return self.B.pop()
        
    def peek(self) -> int:
        """
        Get the front element.
        """
        if self.empty():
            return
        if len(self.B) == 0:
            while len(self.A) != 0:
                self.B.append(self.A.pop())
            return self.B[-1]
        else:
            return self.B[-1]

2.用队列实现栈【leetcode225】

class MyStack:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.A = []
        self.B = []

    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.A.append(x)

    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """ 
        while len(self.A)>1:
            self.B.append(self.A.pop(0))
        temp = self.A.pop(0)
        self.A, self.B = self.B, self.A
        return temp
  
    def top(self) -> int:
        """
        Get the top element.
        """ 
        while len(self.A) > 1:
            self.B.append(self.A.pop(0))
        temp = self.A.pop(0)
        self.B.append(temp)
        self.A, self.B = self.B, self.A
        return temp

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        if len(self.A) == 0:
            return True
        else:
            return False

# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

3.最小栈【leetcode155】

要求实现一个常数时间内能检索到最小值的栈

class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
        self.min_stack = [math.inf]

    def push(self, x: int) -> None:
        self.stack.append(x)
        self.min_stack.append(min(x, self.min_stack[-1]))

    def pop(self) -> None:
        self.stack.pop()
        self.min_stack.pop()

    def top(self) -> int:
        return self.stack[-1]

    def getMin(self) -> int:
        return self.min_stack[-1]



# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

4.用栈实现括号匹配【leetcode20】

class Solution:
    def isValid(self, s: str) -> bool:
        dic = {'(':')','{':'}', '[':']'}
        mystack = []
        for item in s:
            if item in ['(', '{', '[']:
                mystack.append(item)
            if item in [')', '}', ']']:
                if not mystack:
                    return False
                tmp = mystack.pop()
                if dic[tmp] != item:
                    return False
        if mystack:
            return False
        return True

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值