棧的push、pop序列

來源:互聯網
上載者:User

題目:輸入兩個整數序列。其中一個序列表示棧的push順序,判斷另一個序列有沒有可能是對應的pop順序。為了簡單起
見,我們假設push序列的任意兩個整數都是不相等的。
比如輸入的push序列是1、2、3、4、5,那麼4、5、3、2、1就有可能是一個pop系列。因為可以有如下的push和pop
序列:push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,這樣得到的pop序列就是4、5、

3、2、1。但序列4、3、5、1、2就不可能是push序列1、2、3、4、5的pop序列。

思路:

引入一個一個輔助棧先將push數組的一個元素入棧,將在棧頂元素與pop數組的當前位置(位置j從0開始)元素比較,相等則將彈棧,並將pop數組前進一位,不等則將push數組的當前位置(i從0開始)的元素入棧,繼續重複上述步驟,直到棧空。

如果i大於push數組的大小,且j小於pop數組的長度,則說名不配匹配,否則匹配


代碼實現:

int isPopOrder(int *push, int *pop, int len){if(push==NULL || pop==NULL)  //juge the arguement's validityreturn 0;int i=0, j=0;stack<int> s_push;s_push.push(push[i++]);   //push the first element to stackwhile(!s_push.empty() && i<=len){if(s_push.top()==pop[j]){s_push.pop();  //pop stackj++; //add the position of the pop array}else {s_push.push(push[i++]);  }}if(i>len && j<len)return 0;return 1;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.