判断元素出栈,入栈顺序的合法性
public class BooleanStack {
public static boolean booleanStack(int[] pushed,int[] popped){
//定义一个辅助栈
Stack<Integer> stack = new Stack<>();
int i = 0;
for(int num:pushed){
stack.push(num);
while(!stack.isEmpty()&&stack.peek()==popped[i]){
stack.pop();
i++;
}
}
return stack.isEmpty();
}
}
循环队列
//循环队列
public class QueueDemo {
private int[] arr;
private int f = 0;
private int r = 0;
public QueueDemo(int size) {
arr = new int[size];
}
public void add(int value) {
if(f-r == arr.length) {
System.out.println("队列已满");
return;
}
arr[f%arr.length] = value;
f++;
}
public void get() {
if(r == f) {
System.out.println("队列已空");
return;
}
int count = arr[r%arr.length];
r++;
System.out.println(count);
}
}
找最小值
import java.util.Stack;
public class StackMin {
private Stack<Integer> num = new Stack<>();//主栈
private Stack<Integer> min = new Stack<>();//存储最小值的栈
//入栈
public void add(Integer value){
num.push(value);
if(min.empty()){
min.push(value);
}else if(value <= min.peek()){
min.push(value);
}
}
//出栈
public void get(){
if (num.peek() == min.peek()){
min.pop();
}
num.pop();
}
//取出最小值
public void getMin(){
if(!min.isEmpty()){
System.out.println(min.peek());
}
}
}
两个队列实现一个栈
//两个队列实现一个栈
import java.util.LinkedList;
import java.util.Queue;
public class QueueStack {
private Queue<Integer> queue1 = new LinkedList<>();//主队列
private Queue<Integer> queue2 = new LinkedList<>();//辅队列
//插入数据
public void add(Integer value){
queue1.offer(value);
}
Integer data = null;
//先进后出
public void get(){
//将主队列当中的数据放入辅队列,除最后一个外
while (!queue1.isEmpty()){
data = queue1.poll(); //移除元素
if(queue1.isEmpty()){
break;
}
queue2.offer(data);
}
System.out.println(data); //输出元素
//将辅队列当中的数据放回主队列
while (!queue2.isEmpty()){
queue1.offer(queue2.poll());
}
}
}
两个栈实现一个队列
//两个栈实现一个队列
import java.util.Stack;
public class StackQueue {
public static void main(String[] args) {
StackQueue stack=new StackQueue();
stack.add(5);
stack.add(6);
stack.add(8);
stack.add(4);
stack.add(7);
stack.get();
stack.get();
stack.get();
stack.get();
stack.get();
}
private Stack<Integer> stack1=new Stack<>();
private Stack<Integer> stack2=new Stack<>();
public void add(int value) {
stack1.push(value);
}
public void get() {
if(!stack2.empty()) {
System.out.println(stack2.pop());
}else {
while(!stack1.empty()) {
stack2.push(stack1.pop());
}
if(!stack2.empty()) {
System.out.println(stack2.pop());
}
}
}
}