Question

"""linkedQueue.py implements LinkedQueue""" class Node(object): def __init__(self, e, nextNode): self.item, self.next = (e, nextNode) def __str__(self):...

"""linkedQueue.py implements LinkedQueue"""

class Node(object):
def __init__(self, e, nextNode):
self.item, self.next = (e, nextNode)
def __str__(self): return str(self.item)
  
class LinkedQueue(object):
def __init__(self): #O(1)
self._front, self._rear =(None, None)
self._size = 0
  
def enqueue(self, e): # add e to the rear of the queue.
newTail = Node(e, None)
if self.isEmpty():
self._front = newTail
else:
self._rear.next = newTail
self._rear = newTail
self._size += 1

def front(self): # raise exception if it is empty, otherwise return front element
if self.isEmpty():
raise Exception("call LinkedQueue.front() with an empty queue")
return self._front.item

""" raise exception if it is empty, otherwise remove and return
the front element"""
def dequeue(self):
if self.isEmpty():
raise Exception("call LinkedQueue.dequeue() with an empty queue")

data = self._front.item
self._front = self._front.next
if self._size == 1: #only one node, after dequeue it, the queue is empty
self._rear = None
self._size -= 1

def isEmpty(self):
return self._size == 0
def __len__(self) :
return self._size
  
def __str__(self):
  
  
"""def clear(self):
_____________"""

def test(QueueType):
q = QueueType()
for i in range(5):
q.enqueue(10*(i+1))
print(q)
for i in range(3):
print("dequeue: ", q.dequeue())
print (q)

def main():
test(ListQueue)

if __name__ == '__main__':
main()
  

Homework Answers

Answer #1

Here is the completed code for this problem. Since you did not mention anything specific, I have completed the str and clear methods, also fixed dequeue method, and the whole indentation of the code. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.

EDIT: Added time complexities of all methods. Every method except __str__ has a time complexity of O(1) or constant time. str has O(n) time as it needs to traverse the entire queue to create a string of all elements. For some reason I'm unable to reply via comments. Some technical error. So I'm responding here.

#code

class Node(object):
    def __init__(self, e, nextNode): #time complexity: O(1)
        self.item, self.next = (e, nextNode)

    def __str__(self): #time complexity: O(1)
        return str(self.item)


class LinkedQueue(object):
    def __init__(self): #time complexity: O(1)
        self._front, self._rear = (None, None)
        self._size = 0

    def enqueue(self, e): #time complexity: O(1)
        newTail = Node(e, None)
        if self.isEmpty():
            self._front = newTail
        else:
            self._rear.next = newTail
        self._rear = newTail
        self._size += 1

    def front(self): #time complexity: O(1)
        if self.isEmpty():
            raise Exception("call LinkedQueue.front() with an empty queue")
        return self._front.item

    def dequeue(self): #time complexity: O(1)
        if self.isEmpty():
            raise Exception("call LinkedQueue.dequeue() with an empty queue")
        data = self._front.item
        self._front = self._front.next
        if self._size == 1:
            self._rear = None
        self._size -= 1
        return data  # returning removed data

    def isEmpty(self): #time complexity: O(1)
        return self._size == 0

    def __len__(self): #time complexity: O(1)
        return self._size

    def __str__(self): #time complexity: O(n)
        # creating an empty string
        data = ''
        node = self._front  # taking reference to first node
        while node != None:  # looping until node is None
            data += str(node.item)  # appending data of node to data string
            node = node.next  # advancing to next node
            if node != None:  # if it is not empty
                data += ", "  # appending a comma and space
        return data

    def clear(self): #time complexity: O(1)
        self._front, self._rear = (None, None)  # resetting front, rear
        self._size = 0  # resetting size


def test(QueueType):
    q = QueueType()
    for i in range(5):
        q.enqueue(10 * (i + 1))
    print(q)
    for i in range(3):
        print("dequeue: ", q.dequeue())
    print(q)


def main():
    test(LinkedQueue)  # testing LinkedQueue


if __name__ == '__main__':
    main()

#output

10, 20, 30, 40, 50
dequeue:  10
dequeue:  20
dequeue:  30
40, 50
Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None:...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None: """This method adds new value to the tree, maintaining BST property. Duplicates must be allowed and placed in the right subtree.""" Example #1: tree = BST() print(tree) tree.add(10) tree.add(15) tree.add(5) print(tree) tree.add(15) tree.add(15) print(tree) tree.add(5) print(tree) Output: TREE in order { } TREE in order { 5, 10, 15 } TREE in order { 5, 10, 15, 15, 15 } TREE in order {...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {    public static final int DEFAULT_SIZE = 10;    private Object data[];    private int index; code 2 package test; import java.util.*; /* Class Node */ class Node { protected Object data; protected Node link; /* Constructor */ public Node() { link = null; data = 0; } /* Constructor */ public Node(Object d,Node n) { data = d; link = n; } /*...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue class . Call your class Queue. it must be a template class. public class Queue { } I have put a driver program in the module . It is called CircularQueue.java This driver program should then run with your Queue class (no modifications allowed to the driver program). Your Queue class should have at least the following methods: one or more constructors, enqueue, dequeue,...
Instructions: SLLStack (12 pts) ● Using the two properties below, implement the stack interface using the...
Instructions: SLLStack (12 pts) ● Using the two properties below, implement the stack interface using the SLLNode class from Lab 2: ○ top_node → SLLNode object or None ○ size → int, keep track of stack size ● Implement the push( ), pop( ), top( ) methods ● Use SLLNode methods: get_item( ), set_item( ), get_next( ), set_next( ) ● (5 pts) In push(item): ○ Create new SLLNode with item ○ Add new node before top node ○ Update top_node...
Using Inheritance Consider the following (base) class. class Employee(object): def __init__(self, name, salary): self._name = name...
Using Inheritance Consider the following (base) class. class Employee(object): def __init__(self, name, salary): self._name = name self._salary = salary def my_name(self): return self._name def wage(self): return self._salary/26 # fortnight pay Define a new subclass of Employee called Worker. A worker has a manager, who is another employee; their manager is given as an argument to the constructor. You should define a method get_manager that returns the worker’s manager. boss = Employee('Mr. Burns', 1000000) worker = Worker('Waylon Smithers', 2500, boss) Define...
(Please use Java Eclipse) QUESTION 1: For the question below, assume the following implementation of LinkedQueue:...
(Please use Java Eclipse) QUESTION 1: For the question below, assume the following implementation of LinkedQueue: public static final class LinkedQueue<T> implements QueueInterface<T> {     private Node<T> firstNode;     private Node<T> lastNode;     public LinkedQueue() {         firstNode = null;         lastNode = null;     }     @Override     public T getFront() {         if (isEmpty()) {             return null;         }         return firstNode.getData();     }     @Override     public boolean isEmpty() {         return firstNode == null;    ...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
Program will allow anywhere between 1 and 6 players (inclusive). Here is what your output will...
Program will allow anywhere between 1 and 6 players (inclusive). Here is what your output will look like: Enter number of players: 2 Player 1: 7S 5D - 12 points Player 2: 4H JC - 14 points Dealer: 10D Player 1, do you want to hit? [y / n]: y Player 1: 7S 5D 8H - 20 points Player 1, do you want to hit? [y / n]: n Player 2, do you want to hit? [y / n]: y...
Python: Complete the function create_bfs_graph using python. Do not use any libraries def create_bfs_graph(): """ Initializes...
Python: Complete the function create_bfs_graph using python. Do not use any libraries def create_bfs_graph(): """ Initializes the undirected graph from the lecture    Uses the add_edge method    Returns Graph object of the lecture graph Example use: >>> ex_graph = create_bfs_graph() >>> [x in ex_graph.children_of('Jared') for x in ['John', 'Helena', 'Donald', 'Paul']] [False, False, True, True] >>> ex_graph = create_bfs_graph() >>> [x in ex_graph.children_of('Helena') for x in ['John', 'Helena', 'Donald', 'Paul']] [True, False, False, True] """ # DON'T CHANGE ANYTHING...
Data Structures using C++ Consider the following class #ifndef LINKEDQUEUETYPE_H #define LINKEDQUEUETYPE_H #include <iostream> #include <new>...
Data Structures using C++ Consider the following class #ifndef LINKEDQUEUETYPE_H #define LINKEDQUEUETYPE_H #include <iostream> #include <new>    #include <cstdlib> #include "QueueADT.h" using namespace std; // Definition of the node template <class ItemType> struct NodeType {        ItemType info;        NodeType<ItemType> *next; }; template <class ItemType> class LinkedQueueType: public QueueADT<ItemType> { public:        // Constructor        LinkedQueueType();           // Default constructor.           // Post: An empty queue has been created. queueFront = NULL;           //       queueBack = NULL;...