Search in singly linked list
Write a Program to search an element in a singly linked list
Solution
using System;
namespace LinkedListOpearation
{
class Program
{
public static void Main()
{
var linkedList = new LinkedList();
linkedList.Add(6);
linkedList.Add(1);
linkedList.Add(5);
linkedList.Add(1);
linkedList.Add(3);
linkedList.Add(9);
Console.WriteLine("Sorted Linked List is:");
linkedList.Print(linkedList.Head);
linkedList.SearchNode(3);
Console.ReadLine();
}
}
public class LinkedList
{
public Node Head;
public int Size;
public void Add(int data)
{
var node = new Node(data) {Next = Head};
Head = node;
Size++;
}
public void SearchNode(int data)
{
var current = Head;
var i = 1;
var flag = false;
if (Head == null)
return;
while (current != null)
{
if (current.Data == data)
{
flag = true;
break;
}
i++;
current = current.Next;
}
if (flag)
Console.WriteLine("Element is present in the list at the position : " + i);
else
Console.WriteLine("Element is not present in the list");
}
public void Print(Node head)
{
while (head != null)
{
Console.WriteLine(head.Data);
head = head.Next;
}
}
}
public class Node
{
public int Data;
public Node Next;
public Node(int data)
{
Data = data;
}
}
}