CSCI 150 - Foundations of Computer Science
Spring 2013
Programming Exercises: Queues and Linked Lists
Here is one implementation of a Queue:
class Queue1:
def __init__(self):
self.q = []
def add(self, item):
self.q.append(item)
def remove(self):
return self.q.pop(0)
def isEmpty(self):
return len(self.q) == 0
We can test its performance using the following function:
import time
def timeTester(queue, n):
start = time.time()
for i in range(0, n):
queue.add(i)
while not queue.isEmpty():
queue.remove()
return time.time() - start
Test it using the following commands:
timeTester(Queue1(), 100000)
timeTester(Queue1(), 200000)
The way that Queue1 is implemented is inefficient. Removals
take too long. Here is another approach, which is designed to allow fast
removal:
class Queue2:
def __init__(self, lst = []):
self.front = self.back = None
for elt in lst:
self.add(elt)
def __repr__(self):
lst = []
ptr = self.front
while ptr != None:
lst.append(ptr.value)
ptr = ptr.next
return "Queue2(" + str(lst) + ")"
def add(self, item):
if self.isEmpty():
self.front = self.back = Node(item)
else:
n = Node(item)
self.back.next = n
self.back = n
def remove(self):
pass # Your code here
def isEmpty(self):
return self.front == None
class Node:
def __init__(self, value):
self.value = value
self.next = None
def queueWorks(q, n=10):
lst = []
for i in range(n):
q.add(i)
lst.append(i)
for i in range(len(lst)):
if lst[i] != q.remove():
return False
return q.isEmpty()
Your exercise is:
- Implement the
remove() method.
- If
queueWorks(Queue2()) is True, your solution works.
- Run the time test with
Queue2 to see if performance improves.