思路:如果下乙個彈出的數字剛好是棧頂數字,則直接彈出。若下乙個彈出的數字不在棧頂,則把壓棧序列中還沒有入棧的數字壓入輔助棧,直到把下乙個需要彈出的數字壓入棧頂為止。若所有的數字都壓入棧了仍沒有找到下乙個彈出的數字,則表明該序列不可能滴乙個彈出序列。
**:
#include "stdafx.h"
#include #include using namespace std;
bool ispoporder(int *ppush, int *ppop, int nlength)
stacks;
s.push(ppush[0]);
int npop_index = 0;
int npush_index = 1;
while (npop_index < nlength)
if (s.top() == ppop[npop_index])
else
}return true;
}int _tmain(int argc, _tchar* argv)
; int npop1[5] = ;
int npop2[5] = ;
int npop3[5] = ;
int npop4[5] = ;
cout << ispoporder(npush, npop1, 5) << endl;
cout << ispoporder(npush, npop2, 5) << endl;
cout << ispoporder(npush, npop3, 5) << endl;
cout << ispoporder(npush, npop4, 5) << endl;
system("pause");
return 0;
}
棧 面試題31 棧的壓入 彈出序列
我們使用乙個棧stack來模擬該操作。按照 popped 中的順序模擬一下出棧操作,如果符合則返回 true,否則返回 false。這裡用到的貪心法則是如果棧stack的棧頂元素stack.peek popped 序列中下乙個要 pop 的值,則應立刻將該值 pop 出來。最後檢查棧是否為空。cla...
面試題22 棧的壓入彈出序列
題目 輸入兩個整數序列,第乙個序列表示棧的壓入順序,請判斷第二個序列是否為該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的乙個彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。思路 如果下乙個彈出的數字剛好...
面試題22 棧的壓入 彈出序列
題目 輸入兩個整數序列,第乙個序列表示棧的壓入順序,請判斷第二個序列是否為該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入序列,序列4,5,3,2,1,是該壓棧序列對應的乙個彈出序列。但4,3,5,1,2就不可能是該壓棧序列的彈出序列。棧是一種 後進先出 lifo...