225.用队列实现栈

225. 用队列实现栈

方法一:使用一个队列实现栈

思路:队列为先进先出的数据结构,栈为先进后出的数据结构,用队列实现栈,即要遵循队列的先进先出规则(即对头的数先出,此处注意:将队列想成一个容器,容器中东西先从头部出来,至于东西的顺序可以自己改变),通过遵循队列的操作来实现栈的思想/功能

1. push()实现:将先进队列的数放入队列的尾部,后进队列的数放入队列头部(通过顺序调换实现)

2. pop()实现:直接弹出队列的头部数据即可实现栈的先进后出功能

3. top()实现:获取队列的头部数据

4. empty()实现:直接判断队列是否为空即可判断队列是否为空

class MyStack:

    def __init__(self):
        self.que1 = []                   #用列表模拟队列
        #self.que = collections.deque()  #创建双向队列,能快速的在两端进行插入和删除元素,性能比列表优
    def push(self, x: int) -> None:
        n = len(self.que1)
        self.que1.append(x)
        for i in range(n):
            self.que1.append(self.que1.pop(0))  #使用pop(0)获得最左边的数——用列表模拟队列

    def pop(self) -> int:
        num = self.que1[0]
        self.que1.pop(0)
        return num

    def top(self) -> int:
        return self.que1[0]

    def empty(self) -> bool:
        return not self.que1   #比判断语句更节省时间



# 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()

方法二:使用两个队列实现栈

思路:主队列用来装最后队列数九反转后的结果,辅助队列用来实现数据的反转,当数据反转后,将辅助队列的数据放入主队列,最后通过对主队列的操作来实现栈的思想

class MyStack(object):

    def __init__(self):
        self.que1 = collections.deque()   #主队列
        self.que2 = collections.deque()   #辅助队列

    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        self.que2.append(x)
        while self.que1:
            self.que2.append(self.que1.popleft())
        self.que1,self.que2 = self.que2,self.que1


    def pop(self):
        """
        :rtype: int
        """
        return self.que1.popleft()

    def top(self):
        """
        :rtype: int
        """
        return self.que1[0]

    def empty(self):
        """
        :rtype: bool
        """
        return not self.que1

两点注意:

1. 队列的创建有两种,第一:通过列表模拟队列,第二:通过collections模块的deque()创建双向队列

collections模块deque()的使用,参考:(33条消息) Python collections模块之deque()详解_chl183的博客-CSDN博客https://blog.csdn.net/chl183/article/details/106958004

python的deque(双向)队列详解 - 然终酒肆 - 博客园 (cnblogs.com)https://www.cnblogs.com/ranzhong/p/12438841.html

2.判断队列、列表、元组、字典、集合、字符串是否为空时,可直接使用if not 队列/列表/.....或者if 队列/列表/...

以下是使用两个队列实现的 Kotlin 代码: ``` import java.util.* class MyStack() { private val queue1 = LinkedList<Int>() private val queue2 = LinkedList<Int>() private var topElement: Int? = null /** Push element x onto stack. */ fun push(x: Int) { queue2.offer(x) topElement = x while (!queue1.isEmpty()) { queue2.offer(queue1.poll()) } val temp = queue1 queue1 = queue2 queue2 = temp } /** Removes the element on top of the stack and returns that element. */ fun pop(): Int { val popped = queue1.poll() if (queue1.isEmpty()) { topElement = null } else { topElement = queue1.peek() } return popped } /** Get the top element. */ fun top(): Int { return topElement!! } /** Returns whether the stack is empty. */ fun empty(): Boolean { return queue1.isEmpty() } } ``` 解释一下代码: 我们使用两个队列 `queue1` 和 `queue2` 来模拟。`queue1` 存储中的元素,而 `queue2` 用来在 `push` 操作时暂存元素。 在 `push` 操作中,我们首先把元素 `x` 加入到 `queue2` 中,然后将 `queue1` 中的所有元素依次加入到 `queue2` 中。这样做的目的是为了让 `queue2` 中的元素按照的顺序排列,即最后加入的元素在队首,而最先加入的元素在队尾。然后我们将 `queue2` 和 `queue1` 交换,这样 `queue1` 中的元素就按照的顺序排列了。 在 `pop` 操作中,我们直接从 `queue1` 中弹出队首元素即可。如果 `queue1` 变为空队列,则将 `topElement` 置为 `null`。 在 `top` 操作中,我们返回 `topElement`,它记录了顶元素的值。 在 `empty` 操作中,我们判断 `queue1` 是否为空即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值