[Tutor] confused by linked queue

Christopher Spears cspears2002 at yahoo.com
Tue Jul 25 06:54:09 CEST 2006


I am working out of How To Think Like A Computer
Scientist.  I am on the chapter that covers linked
queues.  Here is some code that creates a linked queue
class:

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

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

	def insert(self, cargo):
		node = Node(cargo)
		node.next = None
    		if self.head == None:
			# if list is empty the new node goes first
			self.head = node
		else:
			# find the last node in the list
			last = self.head
			while last.next: 
				last = last.next
				# append the new node
				last.next = node
		self.length = self.length + 1

	def remove(self):
		cargo = self.head.cargo
		self.head = self.head.next
		self.length = self.length - 1
		return cargo

The node is defined by:

class Node:
	def __init__(self, cargo=None, next=None):
		self.cargo = cargo
		self.next = next
		
	def __str__(self):
		return str(self.cargo)

I am confused by the insert class.  I am not quite
sure how it works.  More to the point, I am not sure
if it works:


		>>> from linked_queue import *
>>> queue = Queue()
>>> queue.isEmpty()
True
>>> queue.insert("cargo")
>>> print queue.head
cargo
>>> print queue.length
1
>>> queue.insert("more_cargo")
>>> print queue.length
2
>>> print queue.head
cargo

Where is my second node?  How can I access it?
		 
	
		
	



More information about the Tutor mailing list