类练习题2:堆栈和队列类

来源:互联网 发布:驱动保护编程 编辑:程序博客网 时间:2024/04/30 11:15

该练习题来自(Python 核心编程 第二版)第13章 练习题13-10, 题目如下:


13-10.堆栈和队列。编写一个类,定义一个能够同时具有堆栈(FIFO)和队列(LIFO)操作行为的数据结构。这个类和Perl语言中数组相像。需要实现四个方法:

shift()  返回并删除列表中的第一个元素。

unshift()  在列表的头部"压入"一个新元素。

push()  在列表的尾部加上一个新元素。

pop()  返回并删除列表中的最后一个元素。


下面是我写的该例题代码,供以后参考:

#!/usr/bin/env python class StackQueue(object):    '''Class StackQueue().     The class supports two data structures    for both stack and queue.    '''     def __init__(self):        self.__list = []          def __str__(self):        return str(self.__list)     __repr__ = __str__     def shift(self):        '''        Delete a element from the front of a list.        '''        try:            print self.__list[0]        except IndexError:            print "can't delete a element from a empty list."        else:            self.__list = self.__list[1:]     def unshift(self, element):        '''        Press a new element into the head of the list.        '''        self.__list.insert(0, element)     def push(self, element):        '''        Add a new element to the end of the list.        '''        self.__list.append(element)     def pop(self):        '''        Return and remove the last element in the list.        '''        if hasattr(list, 'pop'):            print self.__list.pop()        else:            try:                print self.__list[-1]            except IndexError:                print "can't delete a element from a empty list."            else:                self.__list = self.__list[:-1] def _test():    a = StackQueue()    print a    a.push(2)    a.unshift(1)    a.push(3)    print a    a.shift()    print a    a.pop()    print a if __name__ == "__main__":    _test()


该脚本可以作为模块导入使用,也可以直接运行,直接运行结果如下:

[]

[1, 2, 3]

1

[2, 3]

3

[2]

0 1