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 answer the following as soon as possible. Thank you. Add the top method in class...
Please answer the following as soon as possible. Thank you. Add the top method in class Stack to the following python code which returns the top item of the stack. Test it. Design top() method using a single queue as an instance variable, and only constant additional local memory within the method bodies. python code: class Stack: def __init__(self): self.q = Queue() def is_empty(self): return self.q.is_empty() def push(self, data): self.q.enqueue(data) def pop(self): for _ in range(self.q.get_size() - 1): dequeued =...
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...
A Queue is a linked list with pointers to both the head of the list as...
A Queue is a linked list with pointers to both the head of the list as well as the tail (or the last element) of the list. Given a queue Q, Q.head gives the head of the queue and Q.tail gives the tail of the queue. Give O(1) time algorithms for the following tasks. Enqueue • Input: A queue Q of distinct integers and a queue element a not in Q. 1 • Output: Q with the element a added...
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...
1. BQUEUE.h #pragma once #include class bqnode { public: int time; bqnode *prev, *next; }; class...
1. BQUEUE.h #pragma once #include class bqnode { public: int time; bqnode *prev, *next; }; class BQUEUE { public: BQUEUE(); ~BQUEUE(); BQUEUE(const BQUEUE &); void Enqueue(int); void Dequeue(); void Print(); private: bqnode * front; //use ONLY one pointer }; 2. BQUEUE.cpp #include "BQUEUE.h" using namespace std; BQUEUE::BQUEUE() { } BQUEUE::~BQUEUE() { } BQUEUE::BQUEUE(const BQUEUE & otherList) { if (otherList.front == NULL) return; front = new bqnode(); bqnode *curr = front; bqnode *oldnode = otherList.front; curr->time = oldnode->time; curr->next = NULL;...
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;...
(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;    ...
Please write the code in Python. Write a program/function in any Object-Oriented programming language that will...
Please write the code in Python. Write a program/function in any Object-Oriented programming language that will implement Queue Abstract Data Type with the following functions/methods.  Any build-in/pre-defined Queue function/library (e.g., java.util.Queue in Java) is NOT allowed to use in your code. push(Element):  insert the input Element (e.g., String or Integer in Java) to the end of the queue. pop(): remove the head element of the queue and print the head element on screen. count():  return the total number of elements in the queue...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT