队列的Python实现(列表实现)

2019/07/29 Python 算法 逃离CSDN

队列的 Python 实现(列表实现)

class Queue(object):
    """队列的定义
    """
    # 队列的初始化,生成空列表
    def __init__(self):
        self.item = []

    # 队列判空方法,返回 True or False
    def isEmpty(self):
        return self.item == []

    # 求队列元素个数方法,返回 int 值
    def size(self):
        return len(self.item)

    # 入队列方法,从列表头部插入
    def enqueue(self, value):
        self.item.insert(0, value)

    # 出队列方法,从列表尾部弹出,返回弹出值
    def dequeue(self):
        return self.item.pop()


def hotpotato(namelist, num):
    """
    利用队列,完成烫手山芋算法(类似于点兵出列)
    先填充满队列,然后做 num 次循环,每次循环将列首出列,再入列,直到最后一个数据直接出列
    当队列的元素只剩一个时,就是最后的 winner
    """
    simqueue = Queue()
    for name in namelist:
        simqueue.enqueue(name)

    while simqueue.size() > 1:
        for i in range(num):
            simqueue.enqueue(simqueue.dequeue())

        simqueue.dequeue()

    return simqueue.dequeue()

# 队列测试
# q = Queue()
# print(q.size(), "\n", q.isEmpty(), "\n", q.enqueue(2), "\n",\
#   q.enqueue("dog"), "\n", q.dequeue(), "\n", q.size(), "\n", q.dequeue())
# 烫手山芋测试
# print(hotpotato(["Bill","David","Susan","Jane","Kent","Brad"],7))

Search

    Table of Contents