1. 用队列实现栈
思路:
入栈:每次都放到不为空的队列当中
出栈:每次出不为空的队列,出size-1个元素
class MyStack {
public Queue<Integer> pu1;
public Queue<Integer> pu2;
//构造方法
public MyStack() {
pu1 = new LinkedList<>();
pu2 = new LinkedList<>();
}
//入栈
public void push(int x) {
if(!pu1.isEmpty()){
pu1.offer(x);
}else if(!pu2.isEmpty()){
pu2.offer(x);
}else{
//此处规定当pu1哈pu2都是空的的时候,放在pu1
pu1.offer(x);
}
}
//出栈
public int pop() {
if(empty()){
return -1;
}
if(!pu1.isEmpty()){
int size = pu1.size();
for(int i = 0;i<size-1;i++){
int x = pu1.poll();
pu2.offer(x);
}
return pu1.poll();
}else{
int size = pu2.size();
for(int i = 0;i<size-1;i++){
int x = pu2.poll();
pu1.offer(x);
}
return pu2.poll();
}
}
//获取栈顶元素
public int top() {
if(empty()){
return -1;
}
if(!pu1.isEmpty()){
int x = 0;
int size = pu1.size();
for(int i = 0;i<size;i++){
x = pu1.poll();
pu2.offer(x);
}
return x;
}else{
int x = 0;
int size = pu2.size();
for(int i = 0;i<size;i++){
x = pu2.poll();
pu1.offer(x);
}
return x;
}
}
//判断栈是不是空的
public boolean empty() {
if(pu1.isEmpty()&&pu2.isEmpty()){
return true;
}
return false;
}
}
2. 用栈实现队列
思路:
入队:都放到第一个栈中
出队:出第二个栈中的元素,当第二个栈为空的时候,就把第一个栈中的元素放到第二个栈中
class MyQueue {
public Stack<Integer> stack1;
public Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
//入队
public void push(int x) {
stack1.push(x);
}
//出队
public int pop() {
if(empty()){
return -1;
}
if(stack2.empty()){
while(!stack1.empty()){
int val = stack1.pop();
stack2.push(val);
}
}
return stack2.pop();
}
//获取队头元素
public int peek() {
if(empty()){
return -1;
}
if(stack2.empty()){
while(!stack1.empty()){
int val = stack1.pop();
stack2.push(val);
}
}
return stack2.peek();
}
//判断队列空不空
public boolean empty() {
if(stack1.empty()&&stack2.empty()){
return true;
}
return false;
}
}
3. 实现一个最小栈
思路:定义两个栈,一个存放所有元素,一个保存最小元素
class MinStack {
public Stack<Integer> stack;
public Stack<Integer> minStack;
//构造方法
public MinStack() {
this.stack = new Stack<>();
this.minStack = new Stack<>();
}
//入栈
public void push(int val) {
stack.push(val);
if(minStack.empty()){
minStack.push(val);
}else{
int x = minStack.peek();
if(x >= val){
minStack.push(val);
}
}
}
//出栈
public void pop() {
if(stack.empty()){
return;
}
int x = stack.peek();
if(x == minStack.peek()){
minStack.pop();
}
stack.pop();
}
//获取栈顶元素
public int top() {
if(stack.empty()){
return -1;
}
return stack.peek();
}
//获取栈顶最小元素
public int getMin() {
if(stack.empty()){
return -1;
}
return minStack.peek();
}
}