Implement Queue using Stacks---LeetCode232

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangljanfxp/article/details/83627280

目录

问题描述

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

猜你喜欢

转载自blog.csdn.net/yangljanfxp/article/details/83627280