//This is the data structure of a node of the linkedList
public class Node
{
public string Name;
public Node Next;
public Node()
{
Name = string.Empty;
Next = null;
}
}
The List!!
public class MyList
{
Node Head = new Node();
int size;
public MyList()
{
size = 0;
// Head = null;
}
//Find the Nth element from the tail
public Node Retrieve(int position)
{
Node temp = Head.next;
//validations
if (size == 0)
return null;
else if (position == 0)
return Head;
else if (position > size || position < 0)
throw new Exception();
else
{
while (temp.next != null)
{
Console.WriteLine(temp.data);
temp = temp.next;
}
Console.WriteLine(temp.data);
return temp;
}
}
Adding a node at the back
public void AddNodeAtBack(int data)
{
Node newNode = new Node();
newNode.data = data;
Node temp = Head.next;
if (size == 0)
{
Head.next = newNode;
size++;
}
else
{
while (temp.next != null)
{
temp = temp.next;
}
temp.next = newNode;
size++;
}
}
Adding a node in front
public void AddNodeAtFront(int data)
{
Node newNode = new Node();
newNode.data = data;
//the validations
if (data == 0)
return;
else
{
if (size == 0)
{
Head.next = newNode;
size++;
}
else
{
newNode.next = Head.next;
Head.next = newNode;
size++;
}
}
}
Find the lenght of the linked list
public int Count()
{
return size;
}
Delete a node from a particular position
public void deleteNode(int pos)
{
Node temp = Head.next;
if (pos > size || pos < 0)
throw new Exception();
else
{
if (size == 0)
throw new InvalidOperationException();
else if (pos == 0)
{
//temp = null;
Head.next = temp.next;
temp = null;
size--;
}
else
{
{
for (int i = 1; i < pos - 1; i++)
{
temp = temp.next;
}
Node temp2 = temp.next;
temp.next = temp2.next;
temp2 = null;
size--;
}
}
}
}
}
Reverse the LinkedList
public void reverseWithoutArray()
{
Node Current = Head;
Node Start = Head.Next;
Node temp = Head.Next;
while (Start.Next != null)
{
temp = Start;
while (temp.Next.Next != null)
{
temp = temp.Next;
}
Current.Next = temp.Next;
temp.Next = null;
Current = Current.Next;
}
Current.Next = Start;
}
Print the nth (3rd) element from the tail of the list
Given an uni-directional linked list, detect infinite loop without using any extra data structure.
Sort the linked list
No comments:
Post a Comment