棰樼洰錛氳緭鍏ヤ袱涓暣鏁板簭鍒椼傚叾涓竴涓簭鍒楄〃紺烘爤鐨刾ush欏哄簭錛屽垽鏂彟涓涓簭鍒楁湁娌℃湁鍙兘鏄搴旂殑pop欏哄簭銆備負浜嗙畝鍗曡搗瑙侊紝鎴戜滑鍋囪push搴忓垪鐨勪換鎰忎袱涓暣鏁伴兘鏄笉鐩哥瓑鐨勩傛瘮濡傝緭鍏ョ殑push搴忓垪鏄?銆?銆?銆?銆?錛岄偅涔?銆?銆?銆?銆?灝辨湁鍙兘鏄竴涓猵op緋誨垪銆傚洜涓哄彲浠ユ湁濡備笅鐨刾ush鍜宲op搴忓垪錛歱ush 1錛宲ush 2錛宲ush 3錛宲ush 4錛宲op錛宲ush 5錛宲op錛宲op錛宲op錛宲op錛岃繖鏍峰緱鍒扮殑pop搴忓垪灝辨槸4銆?銆?銆?銆?銆備絾搴忓垪4銆?銆?銆?銆?灝變笉鍙兘鏄痯ush搴忓垪1銆?銆?銆?銆?鐨刾op搴忓垪銆?br>涓寮濮嬭繕鐪熶笉鐭ラ亾鎬庝箞涓嬫墜錛岀湅浜嗗垎鏋愭墠鐭ラ亾澶ф鏂規硶銆傜劧鍚庡啀鐪嬪弬鑰冧唬鐮?鎰熻榪樻槸鏈変簺澶嶆潅銆傝嚜宸辨兂浜嗕釜紼嶅井綆鍗曠殑鏂規硶,pop闃熷垪榪樺彲鑳芥槸push闃熷垪鐨勫瓙闆嗭細
1 #include <iostream>
2 #include <stack>
3
4 using namespace std;
5 /*!
6 \brief This algorithm demostrates how to judge whether or not a given seqence is
7 possibly a popup sequence providing the pushing sequence.
8 */
9
10 bool IsPopSequence(int* ppush, int pushm, int* ppop, int popm)
11 {
12 int i = 0, j = 0;
13 stack<int> help_stack;
14 while(j < popm)
15 {
16 if (!help_stack.empty() && help_stack.top() == ppop[j])
17 {
18 help_stack.pop();
19 j++;
20 }
21 else if (i < pushm)
22 {
23 help_stack.push(ppush[i++]);
24 }
25 else
26 break;
27 }
28
29 return j >= popm;
30 }
31
32 int main(int argc, char *argv, char *env[])
33 {
34 //int pushseq[] = {1, 2, 3, 4, 5};
35 //int pushseqlen = sizeof(pushseq)/sizeof(pushseq[0]);
36 ////int popseq[] = {4, 5, 3, 2, 1};
37 //int popseq[] = {4, 3, 5, 1, 2};
38 //int popseqlen = sizeof(popseq)/sizeof(popseq[0]);
39
40 int pushseq[] = {1, 2, 3, 4, 5, 6};
41 int popseq[] = {4, 3, 5, 2, 1};
42 int pushseqlen = sizeof(pushseq)/sizeof(pushseq[0]);
43 int popseqlen = sizeof(popseq)/sizeof(popseq[0]);
44
45 cout<<boolalpha<<IsPopSequence(pushseq, pushseqlen, popseq, popseqlen)<<"\n";
46
47 return 0;
48 }

]]>