1. 程式人生 > >Implement Queue using Stacks---LeetCode232

Implement Queue using Stacks---LeetCode232

目錄

問題描述

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