Saturday, February 22, 2020

how to build a link list tree in C#?

i had completed a hackerrank challenge a week ago.. it is quite interesting topic. since C# already provide the LinkList object in the .net framework.

i need to use c# to build my own LinkList class. the recursion is the key to solve this challenge.

here is the sample code. Happy programming


using System;
class Node
{
public int data;
public Node next;
    public Node(int d){
        data=d;
        next=null;
    }
}
class Solution {
public static  Node insert(Node head,int data)
{
      //Complete this method
      Node newNode=new Node(data);
      if(head==null){
         // Console.WriteLine($"{newNode.data} ,{data}");
          return newNode;
        }
      else if(head.next ==null){
          //Console.WriteLine($"{newNode.data} ,{data}");
            head.next=newNode;
       }
       else insert(head.next, data);
      return head;
      //Console.WriteLine($"{head.data} ,{data}");
      //return head;
    }
public static void display(Node head)
{
Node start=head;
while(start!=null)
{
Console.Write(start.data+" ");
start=start.next;
}
}
    static void Main(String[] args) {
Node head=null;
        int T=Int32.Parse(Console.ReadLine());
        while(T-->0){
            int data=Int32.Parse(Console.ReadLine());
            head=insert(head,data);
        }
display(head);
}
}


No comments:

Post a Comment