Search in doubly linked list.

Write a Program to search an element in a doubly linked list

Solution:

using System;

namespace LinkedListOpearation
{
    class Program
    {
        public static void Main()
        {
            var dList = new DoublyLinkedList();
            dList.Add(19);
            dList.Add(82);
            dList.Add(12);
            dList.Add(21);
            dList.Add(43);

            Console.WriteLine("Doubly Linked List: ");
            dList.Print();
            dList.SearchNode(82);
            Console.ReadLine();
        }
    }


    public class DoublyLinkedList
    {
        public int Size;
        public Node Head;
        public Node Tail;

        public void Add(int data)
        {
            var newNode = new Node(data);

            if (Head == null)
            {
                Head = Tail = newNode;
                Head.Previous = null;
                Tail.Next = null;
            }
            else
            {
                Tail.Next = newNode;
                newNode.Previous = Tail;
                Tail = newNode;
                Tail.Next = null;
            }
            Size++;
        }

        public void SearchNode(int value)
        {
            var i = 1;
            var flag = false;

            Node current = Head;

            if (Head == null)
            {
                return;
            }
            while (current != null)
            {
                if (current.Data == value)
                {
                    flag = true;
                    break;
                }
                current = current.Next;
                i++;
            }

            Console.WriteLine(flag ? 
                "Node is present in the list at the position : " + i : 
                "Node is not present in the list");
        }


        public void Print()
        {
            var current = Head;
            if (Head == null)
                return;

            while (current != null)
            {
                Console.WriteLine(current.Data);
                current = current.Next;
            }
        }
    }

    public class Node
    {
        public int Data;
        public Node Next;
        public Node Previous;

        public Node(int data)
        {
            Data = data;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *