Singly Linked List: Lebanese University Faculty of engineering-I-Dpt.: Common Trunk 2 Year - 4 Semester
Singly Linked List: Lebanese University Faculty of engineering-I-Dpt.: Common Trunk 2 Year - 4 Semester
Faculty of engineering-I-
Dpt.: Common Trunk
2nd Year -4th Semester
3 Programming IV
Class for Singly linked list Node
In the following example, LinkedListNode represents a
single node in the linked list, which contains an integer value
and a reference to the next node in the list.
class LinkedListNode
{
public int val;
public LinkedListNode Next = null;
public LinkedListNode()
{ }
public LinkedListNode(int value)
{val=value;
}
}
4 Programming IV
Class for Singly linked list
LinkedList represents the entire linked list, with a Head
property that points to the first node in the list.
The LinkedList has the following methods:
Add(val)
InsertBeforeHead(val)
DeleteHead()
Print()
InsertSorted(int value)
Contains(val)
RemoveDuplicates()
GetTail()
5 Programming IV
Adding a node at the end of a list
class SinglyLinkedList
{ public LinkedListNode Head=new LinkedListNode();
//Add at the End
public void Add(int val)
{ LinkedListNode newNode=new LinkedListNode(val);
if (Head == null)
Head = newNode;
else {
LinkedListNode current = Head;
while (current.Next != null)
{ current = current.Next; }
current.Next = newNode;}
}
val1 val2 val3 null val null
head
New Node
6 Programming IV
Adding a node at the beginning of a list
public void InsertBeforeHead(int val)
{
LinkedListNode newNode = new LinkedListNode(val);
newNode.Next = Head;
Head = newNode;
}
7 Programming IV
Removing First node of a list
public void DeleteHead()
{
if (Head != null)
{
LinkedListNode aux=Head;
Head = Head.Next;
aux=null;
}
}
8 Programming IV
Print all elements of the list
public void Print()
{
LinkedListNode current = Head;
while (current != null)
{
Console.Write(current.val + " ");
current = current.Next;
}
Console.WriteLine();
}
9 Programming IV
Insert inside a sorted list
public void InsertSorted(int value) {
LinkedListNode newNode = new LinkedListNode(value);
if (Head == null || value < Head.val)
{ newNode.Next = Head;
Head = newNode; }
else {
LinkedListNode current = Head;
while (current.Next != null && current.Next.val <
value)
current = current.Next;
newNode.Next = current.Next;
current.Next = newNode;
}
}
10 Programming IV
Testing if a list contains a value
public bool Contains(int value)
{
LinkedListNode current = Head;
while (current != null)
{
if (current.Value == value)
{
return true;
}
current = current.Next;
}
return false;
}
11 Programming IV