fork download
# Queue.py
# Mechanical MOOC
# MIT OCW 6.189 Homework 3
# Exercise 3.6 - Your First Class
# Glenn Richard
# July 21, 2013
import random

class Queue:
    class __Node:
        # private class
        def __init__(self, cargo):
            self.cargo = cargo
            self.next = None
    def __init__(self):
        # Initialize an empty Queue.
        # private attributes
        self.__front = None
        self.__back = None
    def insert(self, cargo):
        # Add a new node to the front to contain the cargo.
        node = self.__Node(cargo)
        if self.__front == None:
            # The Queue was empty.
            self.__front = node
        else:
            # The Queue was not empty.
            self.__back.next = node
        self.__back = node

    def remove(self):
        # Remove the front node and return its cargo.
        if self.__front == None:
            # The Queue was empty, so return None.
            return None
        # The Queue was not empty, so update the pointers and return the front cargo.
        cargo = self.__front.cargo
        self.__front = self.__front.next
        if self.__front == None:
            self.__back = None
        return cargo

    def isEmpty(self):
        # Is the Queue empty?
        return self.__front == None

    def __str__(self):
        # Return a string representation of all the cargo in the Queue nodes.
        qList = []
        p = self.__front
        while p != None:
            qList.append(p.cargo)
            p = p.next
        return "front: " + str(qList) + " :back"

# Create and test a new Queue by adding and removing random integers.
q = Queue()
for i in range(20):
    n = random.randint(0, 9)
    print("n -> " + str(n))
    if n >= 5:
        x = q.remove()
        print("removed " + str(x))
    else:
        q.insert(n)
        print("inserted " + str(n))
    print(q)
Success #stdin #stdout 0.16s 12384KB
stdin
Standard input is empty
stdout
n -> 1
inserted 1
front: [1] :back
n -> 0
inserted 0
front: [1, 0] :back
n -> 1
inserted 1
front: [1, 0, 1] :back
n -> 5
removed 1
front: [0, 1] :back
n -> 5
removed 0
front: [1] :back
n -> 3
inserted 3
front: [1, 3] :back
n -> 8
removed 1
front: [3] :back
n -> 8
removed 3
front: [] :back
n -> 1
inserted 1
front: [1] :back
n -> 9
removed 1
front: [] :back
n -> 2
inserted 2
front: [2] :back
n -> 9
removed 2
front: [] :back
n -> 5
removed None
front: [] :back
n -> 3
inserted 3
front: [3] :back
n -> 9
removed 3
front: [] :back
n -> 0
inserted 0
front: [0] :back
n -> 1
inserted 1
front: [0, 1] :back
n -> 2
inserted 2
front: [0, 1, 2] :back
n -> 0
inserted 0
front: [0, 1, 2, 0] :back
n -> 8
removed 0
front: [1, 2, 0] :back