Thursday, March 26, 2009

C# LinkList program

I just started writing data stucture programs for fun. Here is my first small program in C# which implements Singly LinkList.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SinglyLinkedList
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Getting started with LinkedList");
LinkedList customList = new LinkedList();
customList.Purge();
customList.Prepend(10);
//customList.DisplayListElements();
//Console.ReadKey();
customList.Prepend(5);
customList.Append(15);
customList.Append(20);
customList.InsertElementBefore(20);
customList.InsertElementBefore(10);
customList.InsertElementBefore(5);
customList.DisplayListElements();
Console.ReadKey();
}

class LinkedList
{
private Element head;
private Element tail;
public Element Head
{
get
{
return head;
}
}
public Element Tail
{
get
{
return tail;
}
}

internal class Element
{
internal LinkedList list;
internal int data;
internal Element next;
public Element(LinkedList list, int data, Element next)
{
this.list = list;
this.data = data;
this.next = next;
}
public Element()
{ // do nothing constructor
}
public int Data
{
get
{
return data;
}
set
{
data = value;
}
}
public Element Next
{
get
{
return next;
}
set
{
next = value;
}
}
}
// default constructor of linked list.
public LinkedList()
{
head= null;
tail = null;
}
// purge the linked list and hence we are now pointing it to null.
public void Purge ()
{
head=null;
tail=null;
}
// Prepend method of linked list
public void Prepend(int item)
{
Element tmp = new Element(this, item, head);
if (head == null )
{
tail = tmp;
}
head = tmp;
}
// append method of linked list
public void Append(int item)
{
Element tmp = new Element(this, item, null);
if (head == null)
{
head = tmp;
}
else
{
tail.next = tmp;
}
tail = tmp;
}
// display all elements of list
public void DisplayListElements()
{
Element tmpElement = new Element();
tmpElement = this.head;
int i=0;
do
{
Console.WriteLine("Element{0}: {1}", i, tmpElement.Data);
tmpElement = tmpElement.next;
i++;
}
while (!(tmpElement.next==null));
Console.WriteLine("Element{0}: {1}", i, tmpElement.Data);
}
public void InsertElementBefore(int item)
{
Element tmp = new Element();
Element newItem = new Element(this, 17, null);
tmp = head;
if (head.Data == item)
{
newItem.next = head;
head = newItem;
}
else
{
while (!tmp.Equals(tail))
{
if (tmp.next.Data.Equals(item))
{
newItem.next = tmp.next;
tmp.next = newItem;
break;
}
else
tmp = tmp.next;
}
}

}



} //end of class LinkedList
}
}