C# example-queue data structure

Queue data structure


this is C# example code for a queue data structure. If you are not sure about the queue, i recommend to read: Algorithm and Data Structure tutorial.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{

static void Main(string[] args)
{
Queue<int> myqueue = new Queue<int>();
myqueue.addAtBack(200);
myqueue.addAtBack(201);
myqueue.addAtBack(202);
int del1 =myqueue.removeAtFront ();
if (del1 != 0)
Console.WriteLine("The deleted item:{0}", del1);
myqueue.showall();
Console.ReadLine();
}

class ListNode<T> //T is the generic type.
{
public ListNode(T elem) { val = elem; prev = next = null; }
public T val; //node data
public ListNode<T> prev;//previous link
public ListNode<T> next;//next link
}

class Queue<T>
{
public Queue() { pfirst = plast = null; }
protected ListNode<T> pfirst;
protected ListNode<T> plast;
public void addAtBack(T val)
{
ListNode<T> newnode = new ListNode<T>(val);
//empty list
if (pfirst == null && plast == null)
{
pfirst = newnode;
plast = newnode;
Console.WriteLine("Inserted:{0}", newnode.val);
}
//Add item at the back
else
{

newnode.next = null; //The next link of the item is null.
plast.next = newnode;
newnode.prev = plast;
plast = newnode;
Console.WriteLine("Inserted:{0}", newnode.val);

}



}
public void showall()
{
ListNode<T> t;
if (countitem() > 0)
{
Console.WriteLine("All items in the queue:");
for (t = pfirst; t != null; t = t.next)
{

Console.WriteLine(t.val);
}
}
else Console.WriteLine("No item found!");
}
public int countitem()
{
ListNode<T> i;
int t = 0;
for (i = pfirst; i != null; i = i.next)
{
t = t + 1;
}
return t;
}
public T removeAtFront()
{
T delitem = default(T);
if (countitem() > 0)
{ //make sure the list is not empty.
ListNode<T> temp;

//delete the first item
temp = pfirst;
delitem = temp.val;
pfirst = pfirst.next;
pfirst.prev = null;
temp = null;
}


else Console.WriteLine("No item found");
return delitem;
}

}
}

}






Comments

Name:
Comment:
Enter the text:
CAPTCHA image

....................................................................................................................Home | Forum | About | Contact
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.
Copyright @ 2011-2013 worldbestlearningcenter. All Rights Reserved.
Home Programming Web DB & App Questions Exercises Tips Programs FAQs Download About
Computer-Wbest
Popular Pages
You might like