【Python练习】利用列表List构建栈和队列


栈是一个后进先出(LIFO)的数据结构,通常具有两个基本方法 push和pop,push负责将新元素添加到栈尾,pop负责将栈尾的元素删除。

 

#!/usr/bin/env python
""
stack = []
def push():
    stack.append(raw_input('Enter new string :').strip())

def pop():
    if len(stack) == 0:
        print 'Cannot pop from an empty stack!'
    else:
        print 'Removed [', `stack.pop()` , ']'
    
def viewStack():
    print stack     #
CMDs = {'u':push, 'o':pop, 'v':viewStack}
def showMenu():
    pr = """
    p(U)sh
    p(O)p
    (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 'uovq':
                print 'Invalid option,try again'
            else:
                break
        if choice == 'q':
            break     
        else:
            CMDs[choice]()
if __name__ == '__main__':
    showMenu()                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

队列

队列是一个先进先出(FIFO)的数据结构,通常具有两个基本方法 push和pop,en负责将新元素添加到队列尾部,de负责将队列首部的元素删除。

#!/usr/bin/env python
""
queue = []
def en():
    queue.append(raw_input('Enter new string :').strip())

def de():
    if len(queue) == 0:
        print 'Cannot delete from an empty queue!'
    else:
        print 'Removed [', `queue.pop(0)` , ']'
    
def viewQueue():
    print queue
 

你可能感兴趣的:(python)