ashoktandan

ashoktandan

Single LinkedList in C#

namespace Practice.linkedlist
{
    public class Node
    {
        public string data{get;set;}
        public Node next{get;set;}
        public Node(string data){
            this.data=data;
        }
    }
}

Above is Node class which is basic building block of our implementation.

using System;
using System.Collections.Generic;
namespace Practice.linkedlist
{
public class Linked_List{
    private Node node{get;set;}=null;
    public Linked_List(){
    }
    public void AddNode(string data){
        if(node is null){
           node=new Node(data);
        }else{
            Node _node=node;
            while(_node.next!=null){
                _node=_node.next;
          }
         _node.next=new Node(data);
        }
    }
     public void DeleteNode(string data){
        if(node is null){
           Console.WriteLine("LinkedList is empty.");
        }else{
            Node _prev=null;
            var _curr=node;
            while(_curr!=null){
                if(data==_curr.data){
                    if(_prev is null){ //first object
                        node=node.next;
                    }
                    else{
                        _prev.next=_curr.next;
                    }
                    break;
                }
                _prev=node;
                _curr=node.next;
          }
        }
    }

    public void Display(){
        if(node is not null){
            var _node=node;
            while(_node is not null){
                Console.Write($"{_node.data}");   
                _node=_node.next;             
            }
        }        
    }
}

}
 
Share this