Here is the sample code to create, add, delete, traverse and find methods of a singly linked list:
- Declare a Node class having content and next fields.
- Keep global pointers to tail(Current) and head(Head) nodes.
- SinglyLinkList is generic class so any type of content can be added to this list.
Functionality:
- Add: To add field in linked list.
- AddFirst: To add field at header node in linked list.
- AddLast: To add field at tail node in linked list.
- Contains: Check if linked list contains particular value or not.
- IndexOf: Find first index of particular value in linked list.
- Delete: Delete particular value from linked list.
class SinglyLinkList
{
//Point to current node (last node).
Node Current = null;
// Point to head node.
Node Head = null;
// Node class declaration.
class Node
{
public T content;
public Node next;
}
///
/// Add node as current/last node.
///
/// Node content.
public void Add(T objconent)
{
Node objNode = new Node()
{
content = objconent
};
if (Head == null)
{
Head = objNode;
}
else
{
Current.next = objNode;
}
Current = objNode;
Console.WriteLine("Content {" + objconent.ToString() + "} added.");
}
///
/// Add node as head node.
///
/// Node content.
public void AddFirst(T objconent)
{
Node objNode = new Node()
{
content = objconent
};
if (Head == null)
{
Head = objNode;
}
else
{
objNode.next = Head;
}
Head = objNode;
Console.WriteLine("Content {" + objconent.ToString() + "} added as first node.");
}
///
/// Add node as current/last node.
///
/// Node content.
public void AddLast(T objconent)
{
this.Add(objconent);
Console.WriteLine("Content {" + objconent.ToString() + "} added as last node.");
}
///
/// List down all elements of linked list.
///
public void ListNodes()
{
Node tempNode = Head;
while (tempNode != null)
{
Console.WriteLine(tempNode.content);
tempNode = tempNode.next;
}
}
///
/// Check if node exist.
///
/// Node content.
/// True is exist else false.
public bool Contains(T objconent)
{
return this.IndexOf(objconent) > -1 ? true : false;
}
///
/// Return index of particular node.
///
/// Node content.
/// Index of node content.
public int IndexOf(T objconent)
{
Node tempNode = Head;
int Counter = 0;
while (tempNode != null)
{
if (tempNode.content.Equals(objconent))
{
return Counter;
}
tempNode = tempNode.next;
Counter++;
}
return -1;
}
///
/// Delete node.
///
/// Node content.
public void Delete(T objconent)
{
Node tempNode = Head;
Node preNode = Head;
int Counter = 0;
while (tempNode != null)
{
if (tempNode.content.Equals(objconent))
{
if (Counter == 0)
{
Head = tempNode.next;
}
else
{
preNode.next = tempNode.next;
}
return;
}
preNode = tempNode;
tempNode = tempNode.next;
Counter++;
}
}
}
No comments:
Post a Comment