C++ exercises and solutions: Add item to Queue


Queue

Add item to Queue

Step 2: Adding an item to the Queue

In the Queue data structure, an item is allowed to be added only to the end of the list. To add a new item to Queue, you need to consider two things--empty Queue and none-empty Queue. If the Queue is empty, you simply let the pfirst and plast point to the new item. The next link of the item that doesn't point to other item should be NULL. If the Queue is not empty, you can let the next link of the plast point to the new item and then update the plast to point to the new item.

Adding an item to the end of the Queue  

The C++ code to add an item to Queue is shown below:

//Add ab item the Queue
void addAtBack (int val)
{

 int t;
 ListElem *item;//new element to be Added
 item=(ListElem *)malloc(sizeof(ListElem)); //allocate space
 if(!item) {cout<<"Memory problem..."; exit(100);}

 item->data=val;

//Add a new item to the empty Queue

 if(pfirst==NULL && plast==NULL){
//The first and last item point to the new item when they are null--empty Queue.
  item->next=NULL;
  pfirst=item;
  plast=item;

  cout<<"Added:"<<item->data<<endl;

}

//Add a new item at the end of the Queue
 else
 
{

  item->next = NULL; //The next link of the item is null.
  plast->next = item;
  plast =item;
  cout<<"Added:"<<item->data<<endl;
 
}



}




Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.