Saturday, January 20, 2007

Linked List in C Sharp.NET

I got tones of emails, lately for Linklist and Tree data structure implemetation

Here is a simple Linked List Data structure in C Sharp.NET. A LinkedList will always have two class a LinkedList class and a Node Class.
I have also included most common options to insert and Delete nodes.


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

namespace Algorithms
{
public class LinkedList
{
private Node head;

public LinkedList()
{
head = null;
}
public void Insert(int dataValue)
{
if (head == null)
{
Node nodeInsert = new Node(dataValue);
head = nodeInsert;
nodeInsert.NextNode = null;
}
else
{
Node nodeInsert = new Node(dataValue);
nodeInsert.NextNode = head;
head = nodeInsert;
}
}
public void InsertAtPosition(Node insertNode, int i)
{
if (i == 0)
{
insertNode.NextNode = head;
head = insertNode;
}
else
{
Node currentNode = head;
Node currentNodeNext = head.NextNode;
for (int j = 0; j < i; j++)
{
currentNode = currentNode.NextNode;
currentNodeNext = currentNode.NextNode;
}
if (currentNode != null)
{
currentNode.NextNode = insertNode;
insertNode.NextNode = currentNodeNext;
}


}
}
public void DeleteAtPosition(int i)
{
if (i == 0)
{
head = null;
}
else
{
Node currentNode = head;
Node currentNodeNext = head.NextNode;
for (int j = 0; j < i; j++)
{
currentNode = currentNode.NextNode;
currentNodeNext = currentNode.NextNode;
}
if (currentNode != null)
{
currentNode.NextNode = currentNodeNext.NextNode;
}
}
}
public bool Delete(Node nodeToDelete)
{
bool returnFlag = false;

if (head == null)
returnFlag = false;
else if (head.Equals(nodeToDelete))
{
head = null;
returnFlag = true;
}
else
{
Node checkNode = head;
Node checkNodeNext = head.NextNode;
while (checkNodeNext != null)
{
if (checkNodeNext.Equals(nodeToDelete))
{
checkNode.NextNode = checkNodeNext.NextNode;
checkNodeNext = null;
returnFlag = true;
}
}
}
return returnFlag;

}
public void Print()
{
Node firstNode = head;
while (firstNode != null)
{
Console.Write(firstNode.DataValue + " ");
firstNode = firstNode.NextNode;
}
}
public void Clear()
{
Node checkNode = head;
Node checkNodeNext;

while (checkNode != null)
{
checkNodeNext = checkNode.NextNode;
checkNode = null;
checkNode = checkNodeNext;
}

}

}
public class Node
{
private int dataValue;
private Node nextNode = null;

public Node(int data)
{
dataValue = data;
}
public Node NextNode
{
get
{
return nextNode;
}
set
{
nextNode = value;
}
}
public int DataValue
{
get
{
return dataValue;
}
set
{
dataValue = value;
}
}

}
}

No comments: