使用栈实现队列的下列操作:
- push(x) – 将一个元素放入队列的尾部。
- pop() – 从队列首部移除元素。
- peek() – 返回队列首部的元素。
- empty() – 返回队列是否为空。
package com.zhr.stack;
import java.util.Stack;
/**
* @ Author :zhenghaoran.
* @ Date :Created in 18:38 2019/1/21
* @ Description:232
*/
public class MyQueue {
Stack<Integer> s = new Stack<Integer>();
Stack<Integer> sQueue = new Stack<Integer>();
public MyQueue() {
}
/**
* 我只往第二个stack当做是队列,每次放入的时候都保证已经是队列了dao了一次
*
* @param x
*/
public void push(int x) {
while (!sQueue.isEmpty())
s.push(sQueue.pop());
sQueue.push(x);
while (!s.isEmpty())
sQueue.push(s.pop());
}
public int pop() {
if (sQueue.isEmpty()) return -1;
return sQueue.pop();
}
public int peek() {
if (sQueue.isEmpty()) return -1;
return sQueue.peek();
}
public boolean empty() {
return sQueue.isEmpty();
}
public static void main(String[] args) {
MyQueue obj = new MyQueue();
obj.push(1);
obj.push(2);
obj.peek();
boolean empty = obj.empty();
System.out.println(empty);
}
}
第一种做法只是在push的时候进行控制,保证新加入的元素在最底下这个第二种
package com.zhr.stack;
import java.util.Stack;
/**
* @ Author :zhenghaoran.
* @ Date :Created in 18:38 2019/1/21
* @ Description:两个原则pop栈为空才能导入,第二个要导入就一次性倒完
*/
public class MyQueueTwo {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public MyQueueTwo() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
public void push(int x) {
stackPush.push(x);
//dao();
}
public int pop() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("queue is empty!");
} else if (stackPop.empty()) {
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
//dao();
return stackPop.pop();
}
public int peek() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("queue is empty!");
} else if (stackPop.empty()) {
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
//dao();
return stackPop.peek();
}
public boolean empty() {
dao();
return stackPop.isEmpty();
}
public void dao() {
if (stackPop.isEmpty()) {
while (!stackPush.isEmpty()) {
stackPop.push(stackPush.pop());
}
}
}
public static void main(String[] args) {
MyQueueTwo obj = new MyQueueTwo();
obj.push(1);
obj.push(2);
obj.peek();
boolean empty = obj.empty();
System.out.println(empty);
}
}