数据结构:线性数据结构(2)-队列(栈,队列,deques, 列表)

版权声明:作者:Rookiekk 联系邮箱:[email protected] 欢迎转载或分享,但请务必声明文章出处。 https://blog.csdn.net/qq_18888869/article/details/88134592

队列:FIFO

1.队列的抽象数据类型

队列抽象数据类型由以下结构和操作定义。如上所述,队列被构造为在队尾添加项的有序集合,并且从队首移除。队列保持 FIFO 排序属性。队列操作如下:

  • Queue() 创建一个空的新队列。 它不需要参数,并返回一个空队列。
  • enqueue(item) 将新项添加到队尾。 它需要 item 作为参数,并不返回任何内容。
  • dequeue() 从队首移除项。它不需要参数并返回 item。 队列被修改。
  • isEmpty() 查看队列是否为空。它不需要参数,并返回布尔值。
  • size() 返回队列中的项数。它不需要参数,并返回一个整数。

2.队列的python实现

#队列类的定义
class Queue(object):
    def __init__(self):
        self.items = list()
    
    def enqueue(self, item):
        self.items.append(item)
    
    def dequeue(self):
        return self.items.pop(0)
    
    def isEmpty(self):
        return self.items == []
    
    def size(self):
        return len(self.items)

 3.实例应用

约瑟夫问题与热土豆问题

约瑟夫问题原意:约瑟夫和他的朋友,与39个抵抗战士,在失败前约定41个人围成一圈,从1数到3,数到3的人就自杀,然后从自杀者下一个位置开始重新数,直到全部。约瑟夫需要找两个位置,让他和自己的朋友,成为最后两个人活下来。

热土豆问题:6个小朋友,围成一圈,用一个热土豆(或别的什么东西),数一个数就抛给下一个人,每数到3,手上有土豆的人就站出来,然后继续,问哪个位置的人最后剩下?

#hotpotato
def hotPotato(namelist, num):
    queue = Queue()
    for name in namelist:
        queue.enqueue(name)
    while queue.size() > 1:
        for i in range(num):
            queue.enqueue(queue.dequeue())
        queue.dequeue()
        
    return queue.dequeue()
print(hotPotato(["Bill","David","Susan","Jane","Kent","Brad"],7))

其他线性数据结构:

栈:https://blog.csdn.net/qq_18888869/article/details/88086002

deque:https://blog.csdn.net/qq_18888869/article/details/88137237

列表(链表):https://blog.csdn.net/qq_18888869/article/details/88138785

github代码:https://github.com/makang101/python-data-structure

猜你喜欢

转载自blog.csdn.net/qq_18888869/article/details/88134592