题解:
(1)入栈下标i,出栈下标j,入栈i指向数,出栈一个数与出栈j指向的数进行比较,若相等(2),若不相等,则将出栈的数压回栈中
(2)若相等,将j++,并判断栈是否为空,若为空,i++进行压栈操作;若不为空,则继续出栈比较j指向的当前值,继续(2)
(3)当j<压栈数组的长度,则表示出栈顺序不正确;反之,正确
import java.util.Deque;
import java.util.LinkedList;
public class Test5 {
public static void main(String[] args) {
int[] pushed = {1,2,3,4,5};
int[] popped = {4,5,3,2,1};
System.out.println(validateStackSequences(pushed, popped));
}
public static boolean validateStackSequences(int[] pushed, int[] popped) {
Deque<Integer> qDeque = new LinkedList<>();
if(pushed==null||pushed.length==1){
return true;
}
int i = 0;
int j = 0;
int a;
while(i<pushed.length){//压栈
qDeque.push(pushed[i]);
while(j<popped.length){//出栈
if(!qDeque.isEmpty()){//判断栈是否为空
a = qDeque.pop();//不为空,出栈
}else{
break;
}
if(a == popped[j]){//出栈值与出栈数组j值比较
j++;
continue;
}else{
qDeque.push(a);
break;
}
}
i++;
}
if(j <= popped.length - 1)
return false;
return true;
}
}