python课的小程序~ Queue队列

Question-1:
输入若干字符串,并按输入顺序输出。要求以队列的数据结构方式实现。
参见————堆栈

def push(stack,x):
    stack.append(x)

def pop(stack):
    return stack.pop()

def isEmpty(stack):
    return (stack == [])

def main():
    stack = []
    print "Pushing..."
    x = raw_input("Enter a string: ")
    while x != "":
        push(stack,x)
        x = raw_input("Enter a string: ")
    print "Popping..."
    while not isEmpty(stack):
        print pop(stack),

main()

 

Answer-1:

# 2013.12.31 by Alex YU

def enqueue(queue,x):
	queue.append(x)

def dequeue(queue):
	return queue.pop(0) # pop(0)!!

def main():
	queue =[]
	print 'Enqueueing...'
	x = raw_input('Enter a string: ')
	while x != '':
		enqueue(queue,x)
		x = raw_input('Enter a string: ')
	print '\nDequeueing...'
	for i in range (len(queue)): # need not 'k=len(queue)' 
		print dequeue(queue),

main()

发表评论

电子邮件地址不会被公开。 必填项已用*标注