225. Implement Stack using Queues [easy] (Python)

题目链接

https://leetcode.com/problems/implement-stack-using-queues/

题目原文

Implement the following operations of a stack using queues.

  1. push(x) – Push element x onto stack.
  2. pop() – Removes the element on top of the stack.
  3. top() – Get the top element.
  4. empty() – Return whether the stack is empty.

Notes:

  1. You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
  2. Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  3. You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

题目翻译

太长不翻了。大概就是用队列的push to back, peek/pop from front, size, is empty方法,实现栈的push, pop, top, empty方法。

思路方法

镜像问题:232. Implement Queue using Stacks

思路一

队列是先进先出,每次出只能出队列的头部,而栈是后进先出,所以可以想办法每次把入队的元素弄到队列头部。于是可以考虑在每次push到队列的时候对其他元素做个重新pop和push将当前元素转移到队头。
该方法需要一个队列,push的复杂度O(n),pop的复杂度O(1)。

代码

class Stack(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.stack.insert(0, x)
        for i in range(len(self.stack)-1):
            self.stack.insert(0, self.stack[-1])
            self.stack.pop()

    def pop(self):
        """
        :rtype: nothing
        """
        self.stack.pop()

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

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

思路二

也可以用两个队列实现,将思路一的过程分开。但这时要引入一个变量来记录栈顶元素。
该方法需要两个队列,push的复杂度O(1),pop的复杂度O(n)。

代码

class Stack(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.queue1 = []
        self.queue2 = []
        self.topx = None

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.queue1.insert(0, x)
        self.topx = x

    def pop(self):
        """
        :rtype: nothing
        """
        while len(self.queue1) > 1:
            self.topx = self.queue1.pop()
            self.queue2.insert(0, self.topx)
        self.queue1.pop()
        self.queue1, self.queue2 = self.queue2, self.queue1

    def top(self):
        """
        :rtype: int
        """
        return self.topx

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

思路三

用两个队列,push的复杂度O(n),pop的复杂度O(1)。

代码

class Stack(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.queue1 = []
        self.queue2 = []

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.queue2.insert(0, x)
        while self.queue1:
            self.queue2.insert(0, self.queue1.pop())
        self.queue1, self.queue2 = self.queue2, self.queue1

    def pop(self):
        """
        :rtype: nothing
        """
        self.queue1.pop()

    def top(self):
        """
        :rtype: int
        """
        return self.queue1[-1]

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

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51605052

在实现队列(Queue)的数据结构时,可以使用链表(Linked Lists)和数组(Arrays)这两种常见的数据结构。 a. 使用链接列表(Linked List)实现队列: ```python class Node: def __init__(self, data): self.data = data self.next = None class QueueLL: def __init__(self): self.head = None self.tail = None # 入队操作(enqueue) def enqueue(self, data): new_node = Node(data) if not self.is_empty(): self.tail.next = new_node else: self.head = new_node self.tail = new_node # 出队操作(dequeue) def dequeue(self): if self.is_empty(): return None temp_data = self.head.data self.head = self.head.next if self.is_empty(): self.tail = None return temp_data # 检查队列是否为空 def is_empty(self): return self.head is None # 显示队列元素 def display(self): current = self.head while current: print(current.data, end=" -> ") current = current.next print("None") ``` b. 使用数组实现队列(Array-Based Queue): ```python class QueueArray: def __init__(self, capacity): self.queue = [None] * capacity self.front = -1 self.rear = -1 def is_empty(self): return self.front == self.rear def enqueue(self, data): if (self.rear + 1) % len(self.queue) == self.front: raise Exception("Queue full") if self.is_empty(): self.front = self.rear = 0 else: self.rear = (self.rear + 1) % len(self.queue) self.queue[self.rear] = data def dequeue(self): if self.is_empty(): raise Exception("Queue empty") value = self.queue[self.front] if self.front == self.rear: self.front = self.rear = -1 else: self.front = (self.front + 1) % len(self.queue) return value def display(self): if self.is_empty(): print("Queue is empty") else: index = self.front while True: try: print(self.queue[index], end=" -> ") index = (index + 1) % len(self.queue) except IndexError: break print("None") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值