Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement the Queue using a linked list. Use the following class definition for

ID: 3630481 • Letter: I

Question

Implement the Queue using a linked list. Use the following class definition for the Queue and use the given main function to test your implementation.

#include <iostream>
typedef int QueueElement;

struct node
{
QueueElement data;
node * next;
};

class Queue
{
public:
Queue(); // create an empty Queue
bool empty(); //return true if Queue is empty, otherwise return false
void AddQ(QueueElement x); //add a new value to the back of the Queue
bool Front (QueueElement & x); //retrieve the data at the front of the Queue
void RemoveQ(); //remove the value at the front of the Queue
void display(); //displays the data stored in the Queue from front to back

private:
node * myfront; //pointer to the front of the queue
node * myback; //pointer to the back of the queue
};

int main()
{
Queue Q;

// insert values 10, 20, 30, 40 and 50 onto the Queue
for(int x = 1; x<=5; x++){
int n = x*10;
Q.AddQ(n);
}
//Display the content of the Queue to the screen
Q.display();
cout<<endl<<endl;

//Remove and display each value on the Queue
while (!S.empty())
{ int x;
Q.Front(x);
cout<<endl;
cout<<”Removing --- “ <<x<<endl;
Q.RemoveQ();
Q.display();
}

if (Q.empty())
cout<< “Queue is empty.”<<endl;
}


Explanation / Answer

Queue::Queue()

{

myfront=NULL;

myback=NULL;

}

void Queue::AddQ(QueueElement x)

{

node *newNode=new node;

if(myback==NULL)

{

newNode->data=x;

newNode->next=NULL;

myback=newNode;

myfront=myback;

}

else

{

newNode->data=x;

newNode->next=NULL;

myback->next= newNode;

myback= newNode;

}

cout<<" *** "<<x<<" is inserted into the Queue."<<endl;

}

void Queue::RemoveQ()

{

if(myfront==NULL)

cout<<" *** Error : Queue is empty. "<<endl;

else

{

int deleted_element=myfront->data;

node *temp;

temp=myfront;

myfront=myfront->next;

delete temp;

cout<<" *** "<<deleted_element<<" is deleted from the Queue."<<endl;

}

}

void Queue::display()

{

node *print;

print=myfront;

if(print!=NULL)

cout<<" Values inserted into the Queue are : "<<endl;

else

cout<<" *** Nothing to show. "<<endl;

while(print!=NULL)

{

cout<<" "<<print->data<<endl;

print=print->next;

}

}

bool Queue::empty()

{

if(myfront==NULL&&myback==NULL)

return true;

else

return false;

}

bool Queue::Front(QueueElement & x)

{

if(myfront==NULL)

return false;

else

{

x=myfront->data;

return true;

}

}