题目:
function Stack() {
this.dataStore = []; //保存栈内元素,初始化为一个空数组
this.top = 0; //栈顶位置,初始化为0
this.push = push; //入栈
this.pop = pop; //出栈
this.peek = peek; //查看栈顶元素
this.clear = clear; //清空栈
this.length = length; //栈内存放元素的个数
this.empty = empty; //栈内存放元素的个数
}
function empty() {
if (this.top) {
return false
} else {
return true
}
}
function push(element) {
this.dataStore[this.top++] = element;
}
function pop() {
return this.dataStore[--this.top];
}
function peek() {
return this.dataStore[this.top - 1];
}
function clear() {
this.top = 0;
}
function length() {
return this.top;
}
/*测试stack类的实现*/
// var s = new Stack();
// s.push("aa");
// s.push("bb");
// s.push("cc");
// console.log(s.length()); //3
// console.log(s.peek()); //cc
// var popped = s.pop();
// console.log(popped); //cc
// console.log(s.peek()); //bb
//判断出栈入栈操作合法
// 合法出栈顺序加射程一个队列
let list_a = [4, 3, 2, 1, 0, 9, 8, 7, 6, 5]
let list_b = [4, 6, 8, 7, 5, 3, 2, 9, 0, 1]
let list_c = [2, 5, 6, 7, 4, 8, 9, 3, 1, 0]
let list_d = [4, 3, 2, 1, 0, 5, 6, 7, 8, 9]
let list_e = [1, 2, 3, 4, 5, 6, 9, 8, 7, 0]
let list_f = [0, 4, 6, 5, 3, 8, 1, 7, 2, 9]
let list_g = [1, 4, 7, 9, 8, 6, 5, 3, 0, 2]
let list_h = [2, 1, 4, 3, 6, 5, 8, 7, 9, 0]
function legalExit(list) {
let temp_stack = new Stack();
let n = list.length
for (let i = 0; i < n; i++) {
temp_stack.push(i)
while (!temp_stack.empty() && list[0] == temp_stack.peek()) {
temp_stack.pop()
list.shift()
}
}
if (!temp_stack.empty()) {
return false
}
return true
}
console.log('list_a', legalExit(list_a))
console.log('list_b', legalExit(list_b))
console.log('list_c', legalExit(list_c))
console.log('list_d', legalExit(list_d))
console.log('list_e', legalExit(list_e))
console.log('list_f', legalExit(list_f))
console.log('list_g', legalExit(list_g))
console.log('list_h', legalExit(list_h))
结果: