- 两个栈模拟一个队列
- 两个队列模拟一个栈
- 给定一个序列,判断该序列是否是出栈序列
两个栈模拟一个队列
目的:让序列 1,2,3,4,5. 输出的顺序还是1,2,3,4,5 ,只有栈可以用。
实现思路:建两个栈,先让元素1,2,3,4,5,顺序进入栈1,然后再让元素5,4,3,2,1,进入栈2,这时候栈2的出栈顺序就是1,2,3,4,5了。
public static void twoStackToOneQueue(int[] arr){
//定义两个栈
Stack<Integer> stack1=new Stack<>();
Stack<Integer> stack2=new Stack<>();
//将arr依次入栈1
for (int i=0;i<arr.length;i++){
stack1.push(arr[i]);
}
//将栈1的数据依次入栈2(栈1的元素不为空)
while (!stack1.isEmpty()){
stack2.push(stack1.peek());
stack1.pop();
}
//栈2的元素依次出栈
while(!stack2.isEmpty()){
System.out.println(stack2.peek());//返回栈顶元素,但是不弹出
stack2.pop();
}
}
两个队列模拟一个栈
目的:没有栈的条件下实现1,2,3,4,5;输出5,4,3,2,1。
实现思路:
public static void twoQueueToOneStack(int[] arr){
CircleQueue queue1=new CircleQueue();
CircleQueue queue2=new CircleQueue();
for (int i=0;i<arr.length;i++){
queue1.push(arr[i]);
}//相队列1里面添加数据
int total=arr.length;
while(total!=0){
int count=total;
while(count>1){
queue2.push(queue1.peak());//添加q1的队头
queue1.pop();//
count--;
}
//q1剩余的最后一个
System.out.println(queue1.peek());
queue1.pop();
total--;
count=total;
while(count>1){
queue1.push(queue2.peak());
queue2.pop();
count--;
}
if(count==1){
//q2剩余的最后一个
System.out.println(queue2.peek());
queue2.pop();
total--;
}
}
}
给定一个序列,判断该序列是否是出栈序列
目的:给定一个序列1,2,3,4,5 判断1,2,3,4,5 ;5,4,3,2,1;3,2,5,4,1;4,2,3,1,5等是否是正确的出栈顺序。
实现思路:
建立栈:
inorder[ i ] 入栈,i++, 并将stack.peek() 与 outorder[j] 比较,若相等则出栈,若不等,则inorder[ i ]继续入栈,i++。
此时stack.peek() == outorder[j] ,出栈,j++,继续比较stack.peek() 与 outorder[j]
此时依旧stack.peek() == outorder[j] ,出栈,j++
注:防止空栈异常:防止栈为空时获取栈顶元素stack.peek()与outorder[j]比较
继续入栈inorder[ i ],重复上步,直至 j ==outorder.length 或者 stack.isEmpty() 时结果为true,若不满足上述条件则为 false
public static boolean isOutOrder(int[] inOrder,int[] outOrder) {
if (inOrder == null || outOrder == null || inOrder.length != outOrder.length) {
return false;
}
int i = 0, j = 0; //i遍历inOrder,j遍历outOrder
Stack<Integer> stack = new Stack<>();
for (; i < inOrder.length; ) {
stack.push(inOrder[i++]);//将inOrder[i]入栈后,i立即++ , 此时i为堆栈内元素个数
for (; j < i; ) { //i<j : i小于当前栈内元素个数(i) 防止空栈异常--->出栈若干个后栈为空(防止j减过头)--->不能用j<outOrder .length
if (outOrder[j] == stack.peek()) {
stack.pop();
j++; //只有元素出栈后才j++
} else {
break; //若没有元素相等,则继续比较,不进行j++操作
}
}
}
if (j == outOrder.length) {//或者 if(stack.isEmpty()) 进行判断
return true;
} else {
return false;
}