Python学习之路15——列表实现栈和队列

栈是一种后进先出(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 stack

CMDs = {'u': pushit, 'o':popit, 'v': viewstack}

def showmenu():
	pr = '''
		push<span style="white-space:pre">		</span>#u represent push
		pop<span style="white-space:pre">		</span>#o represent pop
		view<span style="white-space:pre">		</span>#v represent view
		quit<span style="white-space:pre">		</span>#q represent quit
	
		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;
	
		CMDs[choice]()

if __name__ == '__main__':
	showmenu()
</span>

下面是运行结果:

<span style="font-size:14px;">likai@linux-ne7w:~/python> python stack.py 

                push
                pop
                view
                quit

                Enter choice: v

You picked: [v]
[]

                push
                pop
                view
                quit

                Enter choice: p

You picked: [p]
Invalid option, try again

                push
                pop
                view
                quit

                Enter choice: u

You picked: [u]
Enter New string: one

                push
                pop
                view
                quit

                Enter choice: u

You picked: [u]
Enter New string: two

                push
                pop
                view
                quit

                Enter choice: u

You picked: [u]
Enter New string: three

                push
                pop
                view
                quit

                Enter choice: v

You picked: [v]
['one', 'two', 'three']

                push
                pop
                view
                quit

                Enter choice: o

You picked: [o]
Remove [ 'three' ]

                push
                pop
                view
                quit

                Enter choice: v

You picked: [v]
['one', 'two']

                push
                pop
                view
                quit

                Enter choice: p

You picked: [p]
Invalid option, try again

                push
                pop
                view
                quit

                Enter choice: o

You picked: [o]
Remove [ 'two' ]

                push
                pop
                view
                quit

                Enter choice: v

You picked: [v]
['one']

                push
                pop
                view
                quit

                Enter choice: 
</span>


队列

队列是一种先进先出(FIFO)的数据结构

以下是列表模拟队列的代码:

<span style="font-size:14px;">#!/usr/bin/env python

queue = []

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() internaily

CMDS = {'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;">likai@linux-ne7w:~/python> python queue.py 

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: e

You picked: [e]
Enter New string: one

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: e

You picked: [e]
Enter New string: two

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: e

You picked: [e]
Enter New string: three

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: v

You picked: [v]
['one', 'two', 'three']

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: d

You picked: [d]
Removed [ 'one' ]

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: v

You picked: [v]
['two', 'three']

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: d

You picked: [d]
Removed [ 'two' ]

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: v

You picked: [v]
['three']

                (E)nqueue
                (D)equeue
                (V)iew
                (Q)uit

        Enter choice: 
</span>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值