給定入棧順序,判斷出棧順序是否合法
阿新 • • 發佈:2019-01-24
給定一個入棧順序,判斷出棧順序是否有可能發生,所遵循的方法是使用一個輔助棧記錄入棧的元素,當剛開始時候輔助棧為空,入棧元素第一個壓入輔助棧,接下來如果看出棧順序,如果出棧順序的第一個元素和輔助棧的棧頂元素不相等,則繼續把 入棧元素的下一個壓入輔助棧;如果出棧順序的元素和輔助棧的棧頂元素相等則直接將輔助棧的棧頂元素彈出,同時出棧序列向後移動一位。以此類推,如果當入棧元素全部進入輔助棧了,則秩序比較出棧元素是否和棧頂元素相等,相等則彈出,繼續比較下一個出棧元素和棧頂元素;如果出現不相等則返回false.
package stackAndQuence;
import java.util.Stack;
/**
* 判斷一個入棧順序是不是一個出棧順序
*
* @author duola
*
*/
public class pushAndPop {
public static boolean isPopOrder2(int[] push, int[] pop) {
if (push == null || pop == null || push.length <= 0 || pop.length <= 0
|| push.length != pop.length)
return false;
boolean isPossible = false;
Stack<Integer> stack = new Stack<Integer>();
int nextpop = 0;
int nextpush = 0;
while (nextpop < pop.length) {
while (stack.isEmpty() || pop[nextpop] != stack.peek()) {
if (nextpush == push.length)
break;
stack.push(push[nextpush]);
nextpush++;
}
if (stack.peek() != pop[nextpop])
break;
stack.pop();
nextpop++;
}
if (stack.isEmpty())
isPossible = true;
return isPossible;
}
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5 };
int[] b = { 4, 5, 3, 2, 1 };
int[] c = { 4, 3, 5, 1, 2 };
System.out.println(isPopOrder2(a, b));
System.out.print(isPopOrder2(a, c));
}
}