Question

In: Computer Science

Instructions: SLLQueue (13 pts) ● Using the three properties below, implement the queue interface using the...

Instructions:

SLLQueue (13 pts)

● Using the three properties below, implement the

queue interface using the SLLNode class from Lab 2:

head_node → SLLNode object or None

tail_node → SLLNode object or None

size → int, keep track of queue size

● Implement enqueue( ), dequeue( ), front( )

● Use SLLNode methods:

get_item( ), set_item( ), get_next( ), set_next( )

● (5 pts) In enqueue(item):

○ Add new SLLNode (with item) after tail_node

○ Update tail_node and size properties

○ If first item, update head_node property too

● (6 pts) In dequeue( ):

○ If empty, raise Exception('Empty queue: cannot dequeue')

○ Remove head node and return its item

○ Remove any links from old head node

○ Update head_node and size properties

○ If queue becomes empty, reset head_node, tail_node

● (2 pts) In front( ):

○ If empty, raise Exception(Empty queue: no front')

○ Return head node’s item

Code:

class SLLQueue:
   def __init__(self):
       # NOTE: DO NOT EDIT THIS CODE
       # constructor: set properties head_node, tail_node, size
       self.head_node = None
       self.tail_node = None
       self.size = 0

   def __repr__(self):
       # NOTE: DO NOT EDIT THIS CODE
       # string representation of SLLQueue object
       display = []
       node = self.head_node
       while node != None:
           display.append(str(node.get_item()))
           node = node.get_next()
       display = ', '.join(display)
       return 'front [' + display + ']'

   def is_empty(self):
       # NOTE: DO NOT EDIT THIS CODE
       # check if queue is empty
       return self.size == 0

   def enqueue(self,item):
       # TODO: Write your code here...
       # TODO: add new node (with item) after tail_node
       # TODO: update tail_node and size properties
       # TODO: if this is the first node added, update head_node too
      
       pass # TODO: remove this line
      
   def dequeue(self):
       # TODO: Write your code here...
       # TODO: if empty, raise Exception('Empty queue: cannot dequeue')
       # TODO: remove head_node and return its item
       # TODO: remove any links from old head_node (Hint: set to None)
       # TODO: update head_node and size properties
       # TODO: if queue becomes empty, reset head_node and tail_node
      
       pass # TODO: remove this line

   def front(self):
       # TODO: Write your code here...
       # TODO: if empty, raise Exception('Empty queue: no front')
       # TODO: return head_node's item

       pass # TODO: remove this line

Solutions

Expert Solution

# SLLNode class 
class SLLNode:
    def __init__(self,item=None,next_node=None):
        self.item = item
        self.next_node = next_node
    
    def set_item(self,item):
        self.item = item0
    
    def get_item(self):
        return self.item
    
    def get_next(self):
        return self.next_node
    
    def set_next(self,new_node):
        self.next_node = new_node

# SLLQueue class        
class SLLQueue:
    def __init__(self):
       # constructor: set properties head_node, tail_node, size
       self.head_node = None
       self.tail_node = None
       self.size = 0

    def __repr__(self):
       # string representation of SLLQueue object
       display = []
       node = self.head_node
       while node != None:
           display.append(str(node.get_item()))
           node = node.get_next()
       display = ', '.join(display)
       return 'front [' + display + ']'

    def is_empty(self):
       # check if queue is empty
       return self.size == 0

    def enqueue(self,item):
       # add new node (with item) after tail_node
        new_item = SLLNode(item)
        if self.head_node is None: 
            # if this is the first node added, update head_node
            # update tail_node and size properties
            self.head_node = new_item
            self.tail_node = new_item
            self.size = 1
        else:
            self.tail_node.set_next(new_item) # add new node (with item) after tail_node
            self.tail_node = new_item
            self.size = self.size + 1
      
    def dequeue(self):
        if self.is_empty():
            # if empty, raise Exception('Empty queue: cannot dequeue')
            return "Empty queue: cannot dequeue"
        else:
            current = self.head_node
            self.head_node = self.head_node.get_next() # remove and update head_node
            current.set_next(None) # remove any links from old head_node
            self.size = self.size - 1 # update size properties
            if self.is_empty():
                self.tail_node = None # if queue becomes empty, reset tail_node
                self.head_node = None # reset head_node
            return current.get_item() # return the removed item

    def front(self):
        if self.is_empty():
            # if empty, raise Exception('Empty queue: no front')
            return "Empty queue: no front" 
        else:
            return self.head_node.get_item() # return head_node's item

# Testing code           
q = SLLQueue()

q.enqueue("User1")
q.enqueue("User2")
q.enqueue("User3")
q.enqueue("User4")
q.enqueue("User5")
print(q.__repr__())
print(q.dequeue())
print(q.__repr__())
print(q.front())

Hope this will help you !!


Related Solutions

Implement a stack using a single queue. In particular, you are given a queue Q that...
Implement a stack using a single queue. In particular, you are given a queue Q that provides the method Q.size() to return its size at any point and the standard methods of queues (i.e, Q.enqueue(x) and Q.dequeue()). The requirement is to use such methods of Q to implement two methods S.push(x) and S.pop() for a stack S. What are the running times of your methods? Kindly answer using python programming
The BBQ implementation of the Q interface, was a FIFO (First-In, First-Out) queue. Using BBQ as...
The BBQ implementation of the Q interface, was a FIFO (First-In, First-Out) queue. Using BBQ as a guide, write a class called QBB that implements the Q interface as a LIFO (Last-In, First Out) queue. In a FIFO queue elements are removed in the ordered in which they added. In a LIFO queue, elements are removed in the reverse order of arrival. Use a String array as the basis of your implementation. /** * A simplified queue interface to manage...
Implement a queue - C programming, please read the instruction carefully and implement queue.c using dynamic...
Implement a queue - C programming, please read the instruction carefully and implement queue.c using dynamic array structure given dynarray.h and dynarray.c below The second ADT you'll implement for this assignment is a queue. For this assignment, the interface for the queue (i.e. the structures and the prototypes of functions a user of the queue interacts with) is already defined for you in the file queue.h. Your first task in this assignment is to implement definitions for the functions that...
Implement a priority queue using a DoublyLinkedList where the node with the highest priority (key) is...
Implement a priority queue using a DoublyLinkedList where the node with the highest priority (key) is the right-most node. The remove (de-queue) operation returns the node with the highest priority (key). If displayForward() displays List (first-->last) : 10 30 40 55 remove() would return the node with key 55. Demonstrate by inserting keys at random, displayForward(), call remove then displayForward() again. You will then attach a modified DoublyLinkedList.java (to contain the new priorityInsert(long key) and priorityRemove() methods). Use the provided...
Implement the minimum priority queue UnsortedMPQ (using vector) that is a child class of the provided...
Implement the minimum priority queue UnsortedMPQ (using vector) that is a child class of the provided MPQ class. The functions from MPQ that are virtual function (remove min(), is empty(), min(), and insert()) must be implemented in the child classes. The functions remove min() and min() should throw an exception if the minimum priority queue is empty. For the UnsortedMPQ class, you will use a vector to implement the minimum priority queue functions. The insert() function should be O(1) and...
This is for a java program. Payroll System Using Inheritance and Polymorphism 1. Implement an interface...
This is for a java program. Payroll System Using Inheritance and Polymorphism 1. Implement an interface called EmployeeInfo with the following constant variables: FACULTY_MONTHLY_SALARY = 6000.00 STAFF_MONTHLY_HOURS_WORKED = 160 2. Implement an abstract class Employee with the following requirements: Attributes last name (String) first name (String) ID number (String) Sex - M or F Birth date - Use the Calendar Java class to create a date object Default argument constructor and argument constructors. Public methods toString - returning a string...
Using a single queue (linkedQueue), re-implement the concept of Stack ADT, what is the complexity of...
Using a single queue (linkedQueue), re-implement the concept of Stack ADT, what is the complexity of the method push, pop, top, isEmpty, and size. You should not use any extra data structure. Related codes: public interface Stack<E> { int size( ); boolean isEmpty( ); void push(E e); E top( ); E pop( ); } public class LinkedStack<E> implements Stack<E> { private SinglyLinkedList<E> list = new SinglyLinkedList<>( );    public LinkedStack( ) { }    public int size( ) { return...
write a java program to Implement a Priority Queue using a linked list. Include a main...
write a java program to Implement a Priority Queue using a linked list. Include a main method demonstrating enqueuing and dequeuing several numbers, printing the list contents for each.
Implement the stack class (called Stack2) using queue, meaning that the only operations that can be...
Implement the stack class (called Stack2) using queue, meaning that the only operations that can be used are the ones defined in the Queue class. class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) The codes to fill: """ 1. Stack2 class Implement stack data structure using queue """ class Stack2: def __init__(self): # Write your definition for __init__ here def isEmpty(self): #...
C++ Data Structures: Implement a Stack and a Queue using Linked list In this lab you...
C++ Data Structures: Implement a Stack and a Queue using Linked list In this lab you will implement the functionality of a stack and a queue using a linked list. Your program must use of the declaration of the Stack and Queue class in Stack.h and Queue.h You have to implement the functionalities of queue (enq, deq, displayQueue) in a file called Queue.cpp. All the functions in Queue.cpp should follow the prototypes declared in Queue.h. Your code should make use...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT