C语言实现栈的压入弹出序列比较
- 思路:以压入顺序: 1 2 3 4 5,弹出顺序 4 5 3 1 2为列,外层循环遍历弹出序列 4 5 3 1 2,来判断这些元素是否在栈顶。首先对于弹出序列4这个元素,由于一开始是空栈,肯定要不断地入栈,直到栈顶元素为4。然后再将栈顶元素pop出。这时候栈里的元素:1 2 3,未入栈元素 5;弹出序列:5 3 1 2;遍历弹出序列的下一个5,和栈顶元素不相同,继续入栈栈外元素,直到全部入栈或者栈顶元素相同。
- 重点:入栈的判断条件:1.空栈(一定要判断空栈,此时入栈)2.栈顶元素和弹出序列不相同 3.外部有未入栈元素。出栈条件:等于弹出序列。
- 返回出口:全部元素入栈,并且栈顶元素不等于弹出序列。
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pushV int整型一维数组
* @param pushVLen int pushV数组长度
* @param popV int整型一维数组
* @param popVLen int popV数组长度
* @return bool布尔型
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
struct _stack {
int data[1500];
int top;
}st;
void push(int value) {
st.data[st.top++] = value;
}
int pop() {
st.top--;
return st.data[st.top];
}
int s_top() {
return st.data[st.top - 1];
}
bool IsPopOrder(int* pushV, int pushVLen, int* popV, int popVLen ) {
// write code here
st.top = 0;
int i, j=0;
for (i = 0; i < popVLen; i++) {
//当弹出序列 不等于栈顶元素,并且还有元素可以进栈,进行入栈 栈不为空
if ((popV[i] != s_top() && j < pushVLen)||st.top==0){
while (pushV[j] != popV[i]&&j<pushVLen) {
push(pushV[j]);
j++;
}
push(pushV[j++]);
}
//等于栈顶元素 出栈
if (popV[i] == s_top()) {
pop();
}
else {
return false;
}
}
return true;
}