C# OOP: 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#(Csharp) code to add an item to Queue is shown below:

//Add an item the Queue

public void addAtBack(T val)
{
  ListNode<T> newnode = new ListNode<T>(val);
//empty list
 if (pfirst == null && plast == null)
 
{
  newnode.next=null;
  pfirst = newnode;
  plast = newnode;
  Console.WriteLine("Inserted:"+newnode.val);
}
//Insert at the end of the list
 else
 
{
   newnode.next = null; //The next link of the item is null.
   plast.next = newnode;
   plast = newnode;
   Console.WriteLine("Inserted:"+newnode.val);
 
}

}




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.