【问题标题】:Peek Method For Priority Queue优先队列的 Peek 方法
【发布时间】:2015-04-15 00:59:03
【问题描述】:

我正在使用单排序链表实现优先级队列。如何使用 peek 方法?它应该返回队列中下一个项目的副本,而不删除该项目。下一项与出队操作返回的值相同。项目不能从空队列中出列。

我是只是简单地返回我的出队函数的一部分,还是我会做其他事情??

我的代码:

class Node( object ) :
  def __init__( self, cargo = None, next = None ) :
      self.cargo = cargo
      self.next = next

# Creates a new empty unbounded priority queue
class PriorityQueue :


  def __init__( self ) :
      self.length = 0
      self.head = None
      self.last = None

 # Returns a boolean value indicating whether the queue is empty
  def isEmpty( self ) :
      return (self.length == 0)

 # Returns the number of items currently in the queue
 def __len__( self ) :
      return len(self.length)


 # Adds the given item to the queue by inserting it in the proper position 
 # based on the given priority. The new node is appeneded to the end of the
 # linked list
  def enqueue( self, item, priority) :
      newNode = Node(cargo)
      newNode.next = None
      if self.length == 0:
          self.head self.last = newNode
      newNode.next = self.head
      self.head = newNode
      self.last.next = newNode
      self.last = newNode

      temp = self.head
      p = self.head.next
      while p != None :
          if p.cargo > newNode.cargo:
             temp = temp.next
             p = p.next
          break
      newNode.next = temp.next
      temp.next = newNode


 # Removes and returns the next item from the queue, which is the item with 
 # the highest priority. If two or more items have the same priority, those 
 # items are removed in FIFO order. An item cannot be dequeued from an
 # empty queue. The linked list is searched to find the entry with the  
 # highest priority.
  def dequeue( self ) :
      cargo = self.head.cargo
      self.head = self.head.next
      self.length = self.length - 1
      if self.length == 0:
          self.last = None
      return cargo


# Returns a copy of the next item in the queue, without removing the item. 
# The next item is the same value that would be returned by the dequeue 
# operation. An item cannot be dequeued from an empty queue.
  def peek( self ) :

【问题讨论】:

  • return self.head.cargo if self.length else None
  • @Shashank self.length 否则没有?你这是什么意思?
  • 这应该可以帮助您理解它。 stackoverflow.com/questions/394809/…
  • @Shashank 好的,明白了!我写的和你写的一样
  • 酷,大功告成! :)

标签: python


【解决方案1】:
Def Peek():
    if not self.empty():
        return self.head.cargo
    else:
        return None

【讨论】:

  • 这是指dequeue函数还是peek函数?
  • Lindsay 我猜你是 stackoverflow 的新手。在这里,您有任何具体问题。人们无法查看您的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
相关资源
最近更新 更多