2015-04-15 19 views
2

我正在使用單獨排序的鏈接列表實現優先級隊列。我該如何做peek方法?它應該返回隊列中下一個項目的副本,而不會刪除該項目。下一項與出隊操作返回的值相同。一個項目不能從空隊列中出列。針對優先級隊列的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) : 
+0

'回報self.head.cargo如果self.length其他None' – Shashank

+0

@Shashank self.length別的什麼事?你是什​​麼意思? – lindsay

+0

這應該有助於你理解它。 http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator – Shashank

回答

1
Def Peek(): 
    if not self.empty(): 
     return self.head.cargo 
    else: 
     return None 
+0

這是指的是出隊函數還是peek函數? – lindsay

+0

它是Peek()。我的錯。 –

+0

沒問題!謝謝你的回答! – lindsay