亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python實(shí)現(xiàn)隊(duì)列的方法示例小結(jié)【數(shù)組,鏈表】

 更新時(shí)間:2020年02月22日 11:31:16   作者:授我以驢  
這篇文章主要介紹了Python實(shí)現(xiàn)隊(duì)列的方法,結(jié)合實(shí)例形式分析了Python基于數(shù)組和鏈表實(shí)現(xiàn)隊(duì)列的相關(guān)操作技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了Python實(shí)現(xiàn)隊(duì)列的方法。分享給大家供大家參考,具體如下:

Python實(shí)現(xiàn)隊(duì)列

隊(duì)列(FIFO),添加元素在隊(duì)列尾,刪除元素在隊(duì)列頭操作

  • 列表實(shí)現(xiàn)隊(duì)列:利用python列表方法

代碼如下:

# 列表實(shí)現(xiàn)隊(duì)列
class listQueue(object):
  def __init__(self):
    self.items = []

  def is_empty(self):
    return self.items == None

  def size(self):
    return len(self.items)

  # 入隊(duì)
  def enqueue(self, value):
    return self.items.append(value)

  # 出隊(duì)
  def dequeue(self):
    if self.is_empty():
      raise Exception("queue is empty !")
    return self.items.pop(0)

  • 鏈表實(shí)現(xiàn)隊(duì)列:

隊(duì)列的鏈表實(shí)現(xiàn)中,隊(duì)列的入隊(duì)(enqueue)操作類似于鏈表在表尾添加元素;隊(duì)列的出隊(duì)(dequeue)操作類似于在鏈表頭部刪除元素

隊(duì)列初始化中,定義兩個(gè)特殊節(jié)點(diǎn),隊(duì)列頭(head)和隊(duì)列尾(tail),方便進(jìn)行操作

代碼如下:

# 鏈表實(shí)現(xiàn)隊(duì)列
class linkedQueue(object):
  class Node(object):
    def __init__(self, value=None):
      self.value = value
      self.next = None

  def __init__(self):
    self.head = None
    self.tail = None
    #self.head.next = self.tail
    self.length = 0

  def is_empty(self):
    return self.length == 0

  def size(self):
    return self.length

  def enqueue(self, value):
    node = self.Node(value)
    if self.is_empty():
      self.head = node
    else:
      self.tail.next = node
    self.tail = node
    self.length += 1

  def dequeue(self):
    if self.is_empty():
      raise Exception("queue is empty !")
    item = self.head.value
    self.head = self.head.next
    self.length -= 1
    print("出隊(duì)列元素為:",item)
    return item

link = linkedQueue()
link.enqueue(1)
link.enqueue(2)
link.enqueue(3)
link.enqueue(4)
print("隊(duì)列長(zhǎng)度為:",link.size())
link.dequeue()
link.dequeue()

運(yùn)行結(jié)果:

隊(duì)列長(zhǎng)度為: 4
出隊(duì)列元素為: 1
出隊(duì)列元素為: 2

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論