化堆疊為隊
實作一個MyQueue類,該類用兩個堆疊來實作一個佇列,
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 回傳 1
queue.pop(); // 回傳 1
queue.empty(); // 回傳 false
說明:
你只能使用標準的堆疊操作 – 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的,
你所使用的語言也許不支持堆疊,你可以使用 list 或者 deque(雙端佇列)來模擬一個堆疊,只要是標準的堆疊操作即可,
假設所有操作都是有效的 (例如,一個空的佇列不會呼叫 pop 或者 peek 操作),
題意:用兩個堆疊模擬一個佇列,
思路:堆疊是先進后出,佇列是先進先出,所以我們可以先用一個堆疊存著資料,然后用另為一個堆疊存著順序相反的資料,在進行出隊的操作時,我們從那個存放著相反資料的堆疊中操作,這樣就模擬了佇列,
代碼:
class MyQueue {
//存放數字
private Stack<Integer> numStack;
//相反的堆疊,存放資料的順序相反
private Stack<Integer> contraryStack;
/**
* Initialize your data structure here.
*/
public MyQueue() {
// new 出來兩個堆疊
numStack = new Stack<>();
contraryStack = new Stack<>();
}
/**
* Push element x to the back of queue.
*/
public void push(int x) {
//往numStack中存放資料
numStack.push(x);
}
/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
// 呼叫peek(),對contraryStack存放順序相反的資料
peek();
//彈出
return contraryStack.pop();
}
/**
* Get the front element.
*/
public int peek() {
//將numStack的資料全部倒出來放到contraryStack中,這樣順序就反過來的,就模擬了佇列
if (contraryStack.isEmpty()) {
while (!numStack.isEmpty()) {
contraryStack.push(numStack.pop());
}
}
return contraryStack.peek();
}
/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return contraryStack.isEmpty() && numStack.isEmpty();
}
}
完整代碼(含測驗樣例):
package com.Keafmd.day0104;
import java.util.Stack;
/**
* Keafmd
*
* @ClassName: ImplementQueueusingStacks
* @Description: 化堆疊為隊
* @author: 牛哄哄的柯南
* @date: 2021-01-04 21:38
*/
public class ImplementQueueusingStacks {
public static void main(String[] args) {
MyQueue obj = new MyQueue();
obj.push(1);
obj.push(2);
obj.push(3);
// peek 不改變堆疊的值(不洗掉堆疊頂的值),pop會把堆疊頂的值洗掉,
int param_1 = obj.pop();
int param_2 = obj.peek();
boolean param_3 = obj.empty();
System.out.println(param_1);
System.out.println(param_2);
System.out.println(param_3);
}
}
class MyQueue {
//存放數字
private Stack<Integer> numStack;
//相反的堆疊,存放資料的順序相反
private Stack<Integer> contraryStack;
/**
* Initialize your data structure here.
*/
public MyQueue() {
// new 出來兩個堆疊
numStack = new Stack<>();
contraryStack = new Stack<>();
}
/**
* Push element x to the back of queue.
*/
public void push(int x) {
//往numStack中存放資料
numStack.push(x);
}
/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
// 呼叫peek(),對contraryStack存放順序相反的資料
peek();
//彈出
return contraryStack.pop();
}
/**
* Get the front element.
*/
public int peek() {
//將numStack的資料全部倒出來放到contraryStack中,這樣順序就反過來的,就模擬了佇列
if (contraryStack.isEmpty()) {
while (!numStack.isEmpty()) {
contraryStack.push(numStack.pop());
}
}
return contraryStack.peek();
}
/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return contraryStack.isEmpty() && numStack.isEmpty();
}
}
寫作不易,看完如果對你有幫助,感謝點贊支持!
如果你是電腦端,看到右下角的 “一鍵三連” 了嗎,沒錯點它[哈哈]

加油!
共同努力!
Keafmd
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/245659.html
標籤:java
