[算法相关] LeetCode_Implement Queue using Stacks_队列操作

本文详细阐述了如何利用栈的特性实现队列的基本操作,包括入队、出队、获取队首元素和判断队列是否为空。通过将栈分为两个部分并进行特定的元素转移,实现了队列先进先出的特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

232. Implement Queue using Stacks

 

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

Notes:

 

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

如题,这是使用堆中处理队列,

 

push(x),将元素x加入到队列末尾

pop(),从队列中移除顶端元素

peek(),得到队列顶端元素

empty(),判断队列大小是否为空

现在补充关于队列的知识,

1,定义:

队列(Queue)是只允许在一端进行插入,而在另一端进行删除的运算受限的线性表,

(1)允许删除的一端称为队头(Front)。
  (2)允许插入的一端称为队尾(Rear)。
  (3)当队列中没有元素时称为空队列。
  (4)队列亦称作先进先出(First In First Out)的线性表,简称为FIFO表。
     队列的修改是依先进先出的原则进行的。新来的成员总是加入队尾(即不允许"加塞"),每次离开的成员总是队列头上的(不允许中途离队),即当前"最老的"成员离队。

本题的题意是:

 

1)题意为用栈来实现队列。

(2)要用栈来实现队列,首先需要了解栈和队列的性质。

栈:先进后出,只能在栈顶增加和删除元素

队列:先进先出,只能在队尾增加元素,从队头删除元素。这样,用栈实现队列,就需要对两个栈进行操作,这里需要指定其中一个栈为存储元素的栈,假定为stack2,另一个为stack1。当有元素加入时,首先判断stack2是否为空(可以认为stack2是目标队列存放元素的实体),如果不为空,则需要将stack2中的元素全部放入(辅助栈)stack1中,这样stack1中存储的第一个元素为队尾元素;然后,将待加入队列的元素加入到stack1中,这样相当于实现了将入队的元素放入队尾;最后,将stack1中的元素全部放入stack2中,这样stack2的栈顶元素就变为队列第一个元素,对队列的pop和peek的操作就可以直接通过对stack2进行操作即可。

class MyQueue {
     Stack<Integer> s1 = new Stack<>();  
     Stack<Integer> s2 = new Stack<>();  
    // Push element x to the back of queue.
    public void push(int x) {
     s1.push(x); 
    }
    // Removes the element from in front of queue.
    public void pop() {
        if(!s2.isEmpty()) s2.pop();  
        else {  
            while(!s1.isEmpty()) s2.push(s1.pop());  
            s2.pop();  
        }  
    }

    // Get the front element.
    public int peek() {
        if(!s2.isEmpty()) return s2.peek();  
        else {  
            while(!s1.isEmpty()) s2.push(s1.pop());  
            return s2.peek();  
        } 
    }

    // Return whether the queue is empty.
    public boolean empty() {
         return s1.empty() && s2.empty();  
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值