Python學習之路15——列表實現棧和隊列

來源:互聯網
上載者:User

標籤:python   編程   語言   棧   

棧是一種後進先出(LIFO)的資料結構。你可以通過push操作來向棧中添加一個對象,也可以通過pop操作來返回並刪除棧頂對象。

以下是列表類比棧的代碼:

<span style="font-size:14px;">#!/usr/bin/env python'stack.py create a stack'stack = []def pushit():stack.append(raw_input('Enter New string: ').strip())def popit():if len (stack) == 0:print 'Cannot pop from an empty stack!'else:print 'Remove [', repr(stack.pop()), ']'def viewstack():print stackCMDs = {'u': pushit, 'o':popit, 'v': viewstack}def showmenu():pr = '''push<span style="white-space:pre"></span>#u represent pushpop<span style="white-space:pre"></span>#o represent popview<span style="white-space:pre"></span>#v represent viewquit<span style="white-space:pre"></span>#q represent quitEnter choice: '''while True:while True:try:choice = raw_input(pr).strip()[0].lower()except (EOFError, KeyboardInterrupt, IndexError):choice = 'q'print '\nYou picked: [%s]' % choiceif choice not in 'uovq':print 'Invalid option, try again'else:breakif choice == 'q':break;CMDs[choice]()if __name__ == '__main__':showmenu()</span>

下面是運行結果:

<span style="font-size:14px;">[email protected]:~/python> python stack.py                 push                pop                view                quit                Enter choice: vYou picked: [v][]                push                pop                view                quit                Enter choice: pYou picked: [p]Invalid option, try again                push                pop                view                quit                Enter choice: uYou picked: [u]Enter New string: one                push                pop                view                quit                Enter choice: uYou picked: [u]Enter New string: two                push                pop                view                quit                Enter choice: uYou picked: [u]Enter New string: three                push                pop                view                quit                Enter choice: vYou picked: [v]['one', 'two', 'three']                push                pop                view                quit                Enter choice: oYou picked: [o]Remove [ 'three' ]                push                pop                view                quit                Enter choice: vYou picked: [v]['one', 'two']                push                pop                view                quit                Enter choice: pYou picked: [p]Invalid option, try again                push                pop                view                quit                Enter choice: oYou picked: [o]Remove [ 'two' ]                push                pop                view                quit                Enter choice: vYou picked: [v]['one']                push                pop                view                quit                Enter choice: </span>


隊列

隊列是一種先進先出(FIFO)的資料結構

以下是列表類比隊列的代碼:

<span style="font-size:14px;">#!/usr/bin/env pythonqueue = []def enQ():        queue.append(raw_input('Enter New string: ').strip())def deQ():        if len(queue) == 0:                print 'Cannot pop from an empty queue!'        else:                print 'Removed [', repr(queue.pop(0)), ']'def viewQ():        print queue             #calls str() internailyCMDS = {'e': enQ, 'd': deQ, 'v': viewQ}def showmenu():        pr = '''</span>            <span style="font-size:14px;">    (E)nqueue                (D)equeue                (V)iew                (Q)uit        Enter choice: '''        while True:                while True:                        try:                                choice = raw_input(pr).strip()[0].lower()                        except (EOFError, KeyboardInterrupt, IndexError):                                choice = 'q'                        print '\nYou picked: [%s]' % choice                        if choice not in 'devq':                                print 'Invalid option, try again'                        else:                                break                if choice == 'q':                        break                CMDS[choice]()if __name__ == '__main__':                showmenu()</span>
下面是運行結果:

<span style="font-size:14px;">[email protected]:~/python> python queue.py                 (E)nqueue                (D)equeue                (V)iew                (Q)uit        Enter choice: eYou picked: [e]Enter New string: one                (E)nqueue                (D)equeue                (V)iew                (Q)uit        Enter choice: eYou picked: [e]Enter New string: two                (E)nqueue                (D)equeue                (V)iew                (Q)uit        Enter choice: eYou picked: [e]Enter New string: three                (E)nqueue                (D)equeue                (V)iew                (Q)uit        Enter choice: vYou picked: [v]['one', 'two', 'three']                (E)nqueue                (D)equeue                (V)iew                (Q)uit        Enter choice: dYou picked: [d]Removed [ 'one' ]                (E)nqueue                (D)equeue                (V)iew                (Q)uit        Enter choice: vYou picked: [v]['two', 'three']                (E)nqueue                (D)equeue                (V)iew                (Q)uit        Enter choice: dYou picked: [d]Removed [ 'two' ]                (E)nqueue                (D)equeue                (V)iew                (Q)uit        Enter choice: vYou picked: [v]['three']                (E)nqueue                (D)equeue                (V)iew                (Q)uit        Enter choice: </span>




Python學習之路15——列表實現棧和隊列

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.