Question

//This is the implementation file queue.cpp. //This is the implementation of the template class Queue. //The...

//This is the implementation file queue.cpp.
//This is the implementation of the template class Queue.
//The interface for the template class Queue is in the header file queue.h.

#include <iostream>
#include <cstdlib>
#include <cstddef>
#include "queue.h"
using std::cout;


namespace QueueSavitch
{

//Uses cstddef:
template<class T>
Queue<T>::Queue( ) : front(NULL), back(NULL)
{
    //Intentionally empty.
}

//Uses cstddef:
template<class T>
bool Queue<T>::isEmpty( ) const
{
    return (back == NULL);//front == NULL would also work
}

//Uses cstddef:
template<class T>
void Queue<T>::add(T item)
{
    if (isEmpty( ))
       front = back = new Node<T>(item, NULL);//sets both
                  //front and back to point to the only node
   else
   {
       back->setLink(new Node<T>(item, NULL));
       back = back->getLink( );
   }
}

//Uses cstdlib and iostream:
template<class T>
T Queue<T>::remove( )
{
    if (isEmpty( ))
    {
        cout << "Error:Removing an item from an empty queue.\n";
        exit(1);
    }

    T result = front->getData( );

    Node<T> *discard;
    discard = front;
    front = front->getLink( );
    if (front == NULL) //if you removed the last node
        back = NULL;

    delete discard;

    return result;
}

template<class T>
Queue<T>::~Queue( )
{
    T next;
    while (! isEmpty( ))
       next = remove( );//remove calls delete.
}

//Uses cstddef:
template<class T>
Queue<T>::Queue(const Queue<T>& aQueue)
{
    if (aQueue.isEmpty( ))
        front = back = NULL;
    else
    {
        Node<T> *temp = aQueue.front;//temp moves
        //through the nodes from front to back of aQueue.

        back = new Node<T>(temp->getData( ), NULL);
        front = back;
        //First node created and filled with data.
        //New nodes are now added AFTER this first node.

        temp = temp->getLink( );//temp now points to second
                //node or NULL if there is no second node.

        while (temp != NULL)
        {
            back->setLink(new Node<T>(temp->getData( ), NULL));
            back = back->getLink( );
            temp = temp->getLink( );

        }
        //back->link == NULL
    }
}

//Uses cstddef:
template<class T>
Queue<T>& Queue<T>::operator =(const Queue<T>& rightSide)
{
    if (front == rightSide.front)//if the queues are the same
        return *this;
    else //send left side back to freestore
    {
        T next;
        while (! isEmpty( ))
            next = remove( );//remove calls delete.
    }

    if (rightSide.isEmpty( ))
    {
        front = back = NULL;
        return *this;
    }
    else
    {
        Node<T> *temp = rightSide.front;//temp moves 
          //through the nodes from front to back of rightSide.

        back = new Node<T>(temp->getData( ), NULL);
        front = back;
        //First node created and filled with data.
        //New nodes are now added AFTER this first node.

        temp = temp->getLink( );//temp now points to second
                   //node or NULL if there is no second node.

        while (temp != NULL)
        {
            back->setLink(
                     new Node<T>(temp->getData( ), NULL));
            back = back->getLink( );
            temp = temp->getLink( );
        }
        //back->link == NULL;

        return *this;
    }
}

}//QueueSavitch

Question: Modify the code above to include the function count(). This function shall return an integer value representing the number of nodes in the queue. The function does not display the value only returns the value to the caller. Also modify main() to make use of this function when there are no nodes as well as when there is one node and many nodes.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
  • It should have been easier, if queue.h file is provided.
  • Based on the implementation, I have created queue.h file and added count function.
  • Main function uses menu option to test the count functionality.
  • All the functions are self explanatory and provided inline comments appropriately.

queue.h file

//file queue.h.
#ifndef QUEUE_H
#define QUEUE_H

//Declare namespace
namespace QueueSavitch
{
template<class T>
class Node
{
public:
Node(T theData, Node<T>* theLink) : data(theData), link(theLink){}
Node<T>* getLink( ) const { return link; }
const T getData( ) const { return data; }
void setData(const T& theData) { data = theData; }
void setLink(Node<T>* pointer) { link = pointer; }
private:
T data;
Node<T> *link;
};


template<class T>
class Queue
{
public:
//Constructor
Queue( );
Queue(const Queue<T>& aQueue);
//Operator overload
Queue<T>& operator =(const Queue<T>& rightSide);
//destructor
virtual ~Queue( );
//Add an item
void add(T item);
//Remove an item
T remove( );
//Returns true if Queue is empty
bool isEmpty( ) const;

//Returns total number of elements in Queue.
//returns zero, if queue is empty
int count() const;

private:
Node<T> *front;
Node<T> *back;
};

}//QueueSavitch

#endif //QUEUE_H

queue.cpp file

#include <iostream>
#include <cstdlib>
#include <cstddef>
#include "queue.h"
using std::cout;


namespace QueueSavitch
{

//Uses cstddef:
template<class T>
Queue<T>::Queue( ) : front(NULL), back(NULL)
{
//Intentionally empty.
}

//Uses cstddef:
template<class T>
bool Queue<T>::isEmpty( ) const
{
return (back == NULL);//front == NULL would also work
}

//Uses cstddef:
template<class T>
void Queue<T>::add(T item)
{
if (isEmpty( ))
front = back = new Node<T>(item, NULL);//sets both
//front and back to point to the only node
else
{
back->setLink(new Node<T>(item, NULL));
back = back->getLink( );
}
}

//Uses cstdlib and iostream:
template<class T>
T Queue<T>::remove( )
{
if (isEmpty( ))
{
cout << "Error:Removing an item from an empty queue.\n";
exit(1);
}

T result = front->getData( );

Node<T> *discard;
discard = front;
front = front->getLink( );
if (front == NULL) //if you removed the last node
back = NULL;

delete discard;

return result;
}

template<class T>
Queue<T>::~Queue( )
{
T next;
while (! isEmpty( ))
next = remove( );//remove calls delete.
}

//Uses cstddef:
template<class T>
Queue<T>::Queue(const Queue<T>& aQueue)
{
if (aQueue.isEmpty( ))
front = back = NULL;
else
{
Node<T> *temp = aQueue.front;//temp moves
//through the nodes from front to back of aQueue.

back = new Node<T>(temp->getData( ), NULL);
front = back;
//First node created and filled with data.
//New nodes are now added AFTER this first node.

temp = temp->getLink( );//temp now points to second
//node or NULL if there is no second node.

while (temp != NULL)
{
back->setLink(new Node<T>(temp->getData( ), NULL));
back = back->getLink( );
temp = temp->getLink( );

}
//back->link == NULL
}
}

//Uses cstddef:
template<class T>
Queue<T>& Queue<T>::operator =(const Queue<T>& rightSide)
{
if (front == rightSide.front)//if the queues are the same
return *this;
else //send left side back to freestore
{
T next;
while (! isEmpty( ))
next = remove( );//remove calls delete.
}

if (rightSide.isEmpty( ))
{
front = back = NULL;
return *this;
}
else
{
Node<T> *temp = rightSide.front;//temp moves
//through the nodes from front to back of rightSide.

back = new Node<T>(temp->getData( ), NULL);
front = back;
//First node created and filled with data.
//New nodes are now added AFTER this first node.

temp = temp->getLink( );//temp now points to second
//node or NULL if there is no second node.

while (temp != NULL)
{
back->setLink(
new Node<T>(temp->getData( ), NULL));
back = back->getLink( );
temp = temp->getLink( );
}
//back->link == NULL;

return *this;
}
}

//New function Count to return number of elements in queue
//Uses cstddef:
template<class T>
int Queue<T>::count() const
{
//Check if queue empty, if so, return zero
if (isEmpty( ))
return 0;
else
{
//Traverse the queue with front element
Node<T> *current = front;
  
//Intialize temp count to store number of elements
//Since we have front, initialize it to 1
int noofelements = 1;
while(current!=back)
{
//we have back element so increase the count by 1.
noofelements++;
//Go to the next element
current= current->getLink( );
}
//Return the counf
return noofelements;
}
}

}//QueueSavitch

Main.cpp

#include <iostream>
#include "queue.h"
#include "queue.cpp"
using std::cin;
using std::cout;
using std::endl;
//Using the Queue namesapce
using QueueSavitch::Queue;

//Display menu
void printmenu()
{
cout<< "******* MENU *******\n";
cout<< "1. Get Total Elements in Queue\n";
cout<< "2. Add new integer to Queue\n";
cout<< "3. Quit\n";
}

//get user choice
int getChoice()
{
int choice;
cout<< "\nEnter your choice (1-3): ";
cin >> choice;
return choice;
}

//get input for queue
int getQueueInput()
{
int queueinput;
cout<< "\nEnter a integer: ";
cin >> queueinput;
return queueinput;
}

//Main method
int main( )
{
//Declare a INT queue
Queue<int> MyQueue;
  
//user input choice
int choice;
do
{
//Print menu
printmenu();
//Get user choice
choice = getChoice();
switch(choice)
{
//Display count
case 1:
{
cout<<"Total elements in Queue: " << MyQueue.count() << "\n";
break;
}

//Add an integer to queue
case 2:
{
int queueinput = getQueueInput();
MyQueue.add(queueinput);
break;
}
//Quit
case 3:
{
cout<<"Good Bye! See you soon!";
}
}
}while(choice != 3); //Quit
return 0;
}

Sample Output:

Feel free to rate the answer. Let me know if you have any question through comment section. I am happy to answer.

Happy Studying!

Add a comment
Know the answer?
Add Answer to:
//This is the implementation file queue.cpp. //This is the implementation of the template class Queue. //The...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Are based on the following Queue class code segment class QueueFull {/* Empty exception class */};...

    Are based on the following Queue class code segment class QueueFull {/* Empty exception class */}; Class Queue Empty {/* Empty exception class */}; struct Node//Node structure int data;//Holds an integer Node* next;//Pointer to next node in the queue}; Class Queue//Linked node implementation of Queue ADT {Private: Node* front;//Pointer to front node of queue Node* rear;//pointer to last node of queue Public: Queue ()://default constructor initializes queue to be empty -Queue ();//Deallocates all nodes in the queue Void Add (int...

  • Introduction In this lab, you are supposed to implement a graph class with the data structure...

    Introduction In this lab, you are supposed to implement a graph class with the data structure implemented before like linked list and queue. graph The class graph contains three member variables: linkedList *adjacentVertices; //an array of linked list. For a vertice i, adjacentVertices[i] stores the linked list that contains all other vertices connected to vertice i. int numVertices; //The number of vertices in the graph. int maxNumVertices; //The maximum number of vertices the graph can hold. Following public methods are...

  • This is a c++ class utilizing class templates and linked lists and Nodes. I need to...

    This is a c++ class utilizing class templates and linked lists and Nodes. I need to implement the following member function(s) to LinkedBag.cpp. Node.hpp/cpp should be fine but if you feel like there needs to be a change for compilation or testing, feel free to do so but make sure to comment on why it was done. In this case, I need to join the original items with the user items(a_bag). So if the original has {1,2,3} and a_bag has...

  • I need to complete the C++ program for hotel reservation. In the main cpp you have...

    I need to complete the C++ program for hotel reservation. In the main cpp you have to display the hotel information from the hotel.txt based on customer preferences(which can be taken from the User.txt) For example, if the customer's budget is 200$, then only the hotels with prices below that amount should be displayed. Then the user has an option to choose which one to reserve for the particular time(which also can be found in the user.txt) The last two...

  • C++ ((USE STL verison please)) Implement the queue class as shown above. Use your queue to...

    C++ ((USE STL verison please)) Implement the queue class as shown above. Use your queue to store the names of 5 students waiting outside Student Services to meet with advisors. You may want to add more data to each node including student ID, Major, etc. Add a member function displayQueue which displays the contents of the queue. Write the main function to test the queue. CLASS: #ifdef queue_h #define queue_h namespace queues { struct queueNode{ char data; queueNode *link; };...

  • Please answer in C++ Derive a class called Queue from the linked list described in Assignment...

    Please answer in C++ Derive a class called Queue from the linked list described in Assignment 2 (list of Dates). This means the Queue class will inherit all the properties (data and functions) of the linked list. But, since a queue allows pushing only at the back and popping at the front of the list, you will need to prevent the addition in the front and removal at the back. To do this, you must derive the Queue class in...

  • I need help fixing my code.   My output should be the following. Hello, world! : false...

    I need help fixing my code.   My output should be the following. Hello, world! : false A dog, a panic in a pagoda : true A dog, a plan, a canal, pagoda : true Aman, a plan, a canal--Panama! : true civic : true If I had a hi-fi : true Do geese see God? : true Madam, I’m Adam. : true Madam, in Eden, I’m Adam. : true Neil, a trap! Sid is part alien! : true Never odd...

  • How do I pass values to this function? class DynIntQueue { struct QueueNode { int value;...

    How do I pass values to this function? class DynIntQueue { struct QueueNode { int value; QueueNode *next; QueueNode(int value1, QueueNode *next1 = nullptr) { value = value1; next = next1; } }; // These track the front and rear of the queue QueueNode *front; QueueNode *rear; public: // Constructor and Destructor DynIntQueue(); ~DynIntQueue(); // Member functions void enqueue(int); void dequeue(int &); bool isEmpty() const; void clear(); }; main #include <iostream> #include "DynIntQueue.h" using namespace std; int main() {DynIntQueue list;...

  • there show an error in sample.cpp file that more than one instance of overloaded function find...

    there show an error in sample.cpp file that more than one instance of overloaded function find matches the argument list. can you please fix it. and rewrite the program and debug. thanks. I also wrote error below on which line in sample.cpp. it shows on find. #include #include #include "node1.cpp" using namespace main_savitch_5; // node1.h #ifndef MAIN_SAVITCH_NODE1_H #define MAIN_SAVITCH_NODE1_H #include <string> namespace main_savitch_5 {    template<class item>    class node    {    public:        typedef item value_type;   ...

  • Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements...

    Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT