Implement Queue using Stacks---LeetCode232

本文介绍了一种使用两个栈来实现队列数据结构的方法。通过具体的操作如push、pop、peek和empty,详细解释了如何在保持队列先进先出特性的前提下,利用栈的后进先出特性。并提供了完整的Java代码实现。

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

目录

问题描述

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.

用两个栈实现队列的进队操作(push),出队操作(pop:移除队列元素;peek:获取队列元素),判空操作(empty)

解题思路

用两个栈(stack1,stack2)实现队列(queue),队列是先进先出,而栈是先进出;
(1)push,很显然直接在stack1.push()就可以实现;
(2)pop,是删除队列元素,这时候队首位于stack1的栈底,将stack1中n-1个元素全部出栈,然后进入stack2;在stack1中剩下的元素直接出栈,完成删除操作;当然做完pop操作后,记得将stack2中元素,重新“入队”到stack1中;
(3)peek,与pop操作类似,不过这里不再是n-1个元素,而是n,没有移除操作;
(4)empty,由于stack2只是暂时存放而已,所以这里直接检查stack1就好;

代码

import java.util.Stack;

/**
 * 
 * @author 22072
 *	用两个栈实现队列
 *
 */
public class MyQueue {
	Stack<Integer> s1;
	
	/** Initialize your data structure here. */
    public MyQueue() {
    	s1=new Stack<Integer>();
    }
    
    /** 队列的进队操作 Push element x to the back of queue. */
    public void push(int x) {
    	s1.push(x);
        
    } 
    /** 队列的删除操作:从队列前面删除元素  Removes the element from in front of queue and returns that element. */
    public int pop() {
    	Stack<Integer> s2=new Stack<>();
        int length = s1.size();
        for(int i=0;i<length-1;i++){
        	s2.push(s1.peek());
        	s1.pop();
        }
        int res=s1.peek();
        s1.pop();
        int temsize = s2.size();
        for(int i=0;i<temsize;i++){
        	s1.push(s2.peek());
        	s2.pop();
        }
        return res;
    }
    
    /** 获取前面的元素Get the front element. */
    public int peek() {
    	Stack<Integer> s2=new Stack<>();
        int length = s1.size();
        for(int i=0;i<length-1;i++){
        	s2.push(s1.peek());
        	s1.pop();
        }
        int res=s1.peek();
        s1.pop();
        s2.push(res);
        int temsize = s2.size();
        for(int i=0;i<temsize;i++){
        	s1.push(s2.peek());
        	s2.pop();
        }
        return res;
    }
    
    /**返回队列是否为空 Returns whether the queue is empty. */
    public boolean empty() {
    	return s1.isEmpty();
    }

}

可以看看这篇微信文章,解法不太一样,但是思路基本一致,而且配有图片说明https://mp.weixin.qq.com/s?__biz=MzI2NjA3NTc4Ng==&mid=2652080519&idx=1&sn=745ce20aacd91f667d54b5a596c1a1e2&chksm=f1748262c6030b7417fb525083e523ffe8bd3d76240bd9c2a0d5aa5d3d02356f2ddd666b5efe&scene=0#rd

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值