Newbie - chapter 19 in "How to think like a CS in python"
MooMaster
ntv1534 at gmail.com
Wed Jul 20 13:33:55 EDT 2005
Well, being a lowly CS student myself this sounded like fun, so I went
ahead and took the challenge. The first thing you have to consider is
how to add the new element to the list. Obviously you have to iterate
through the list, find the first element that the new one is greater
than, and insert this one before it while keeping the list structure
intact. You must also remember to update the head if necessary, and add
at the end if the element to be added is less than what is already in
the list...So this is what I came up with:
First of all, however, add this to your Improved Queue Class-----
def printQueue(self):
if(self.isEmpty()):
print "Empty"
else:
pointer = self.head
while(pointer != None):
print str(pointer.cargo)
pointer = pointer.next
Then------
class PriorityQueueList(ImprovedQueue):
def __init__(self):
ImprovedQueue.__init__(self)
def insert(self, cargo):
newNode = Node(cargo)
if self.length == 0:
self.head = self.last = newNode
else:
#iterate through the list, keeping a reference to a
node and the node before it
tracker = self.head
while(tracker !=None):
copy2 = tracker.prev
if(newNode.cargo > tracker.cargo):
#add the new node by updating links, then update
head while keeping list intact
tracker.prev = newNode
newNode.next = tracker
self.head = newNode
newNode.prev = copy2
if(copy2 !=None):
copy2.next = newNode
break
else:
tracker = tracker.next
#if a repeat element is added
#we want to add to end to preserve the queue structure,
thus if the element hasn't
#been added at this point it should be added at the end
if(newNode.prev ==None and newNode.next ==None):
last = self.last
last.next = newNode
self.last = newNode
self.length = self.length + 1
This produces the following output-----
>>> l = PriorityQueueList()
>>> l.insert(1)
>>> l.insert(2)
>>> l.insert(1)
>>> l.printQueue()
2
1
1
>>> l.insert(10)
>>> l.printQueue()
10
2
1
1
Hope this helps!
More information about the Python-list
mailing list