题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pushV int整型一维数组 * @param pushVLen int pushV数组长度 * @param popV int整型一维数组 * @param popVLen int popV数组长度 * @return bool布尔型 */ #include <stdbool.h> #include <stdlib.h> bool IsPopOrder(int* pushV, int pushVLen, int* popV, int popVLen ) { // write code here int curPush = -1; //压栈的当前位置 int curPop = 0; //弹栈的当前位置 int* st = (int*)malloc(sizeof(int)*pushVLen); //模拟栈 int curSt = -1; while(curPop < popVLen){ if(curSt >= 0 && st[curSt] == popV[curPop]){ //如果st栈顶与popV[curPop]相同,st弹出 curSt--; //st弹出 curPop++; continue; //处理连续弹出的情况 } if(curPush < pushVLen-1) //pushV还没空,继续压到st st[++curSt] = pushV[++curPush]; //将pushV的curPush压入st else //pushV空了,对比st栈顶与popV栈顶,如果不相同则false if(st[curSt] != popV[curPop]) return false; } if(curPop == popVLen) //如果弹栈popV全部弹出,表明弹栈序列可用 return true; else return false; }