1. 用两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int a;
if(stack2.empty()){
while(!stack1.empty()){
a=stack1.top();
stack2.push(a);
stack1.pop();
}
}
a=stack2.top();
stack2.pop();
return a;
}
private:
stack<int> stack1;
stack<int> stack2;
};
2. 用队列实现栈
思路:同样是两个队列实现栈的push和pop操作。分为数据队列和辅助队列,基本没有什么难点,正常往数据队列push,pop时,将数据队列的数据移到辅助队列,直至剩下最后一个队列尾元素,POP出,并将辅助队列在push回数据队列中
package com.sxt.test.java;
public class Queue2Stack {
/**
* 用队列的入队和出队
* 来实现栈的入栈和出栈
* */
Queue queue1 = new Queue();//主要存放数据
Queue queue2 = new Queue();//辅助
public void push(Object o) {
queue1.add(o);
}
public Object pop() {
Object o = null;
while(queue1.length()>1) {
queue2.add(queue1.poll());
}
if(queue1.length()==1) {
o = queue1.poll();
while(queue2.length()>0) {
queue1.add(queue2.poll());
}
}
return o;
}
public int length() {
return queue1.length();
}
}
3. 包含min函数的栈
import java.util.Stack;
public class Solution {
Stack<Integer> stack = new Stack();
int min = 9999;
public void push(int node) {
if(node<min)
{
stack.push(min);
min = node;
}
stack.push(node);
}
public void pop() {
if(stack.peek() == min)
{
stack.pop();
min = stack.peek();
}
stack.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return min;
}
}
4. 判断栈的压入、弹出序列是否正确
算法思想:就是将自己判断栈的弹出序列是否合法的
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA.length == 0 || popA.length == 0)
{
return false;
}
Stack<Integer> stack = new Stack<Integer>();
int index = 0;
int len = pushA.length;
for(int i = 0;i<len;++i)
{
stack.push(pushA[i]);
while(!stack.isEmpty() && stack.peek() == popA[index])
{
stack.pop();
++index;
}
}
return stack.isEmpty();
}
}