Sunday, 17 September 2017

Find the middle of a given linked list

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestAlgo
{
    class Program
    {
        static void Main(string[] args)
        {
            LinkedLst objLst = new LinkedLst();
            objLst.AddItem(1);

            objLst.AddItem(2);
            objLst.AddItem(3);
            objLst.AddItem(4);
            objLst.AddItem(5);


            objLst.PrintLLinkedList(objLst);
            objLst.PrintMiddle(objLst);
}
}

---------------------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestAlgo
{
  public  class LinkedLst
    {
      Node head;
      public class Node
      {
        public int data;
        public Node nxt;
        public Node(int d)
        {
            this.data = d;
            this.nxt = null;
        }

      }

      public void AddItem(int d)
      {
          Node newNode = new Node(d);
          newNode.nxt = head;
          head = newNode;

      }

      public void PrintMiddle(LinkedLst lst)
      {

          Node slow = lst.head;
          Node fast = lst.head;

          while (slow != null && fast.nxt!= null)
          {
              slow = slow.nxt;
              
              fast = fast.nxt.nxt;
              if (fast == null)
                  break;

          }

          Console.WriteLine(slow.data);

          //List<int> lstObj = new List<int>();
          
          //Node newNode = lst.head;
          //while (newNode != null)
          //{
          //    lstObj.Add( newNode.data);
          //    newNode = newNode.nxt;
             
          //}
          
          //int middleindex;
          //if (lstObj.Count() == 1)
          //    middleindex = 0;
          //else
          //    middleindex = lstObj.Count() / 2;
          //Console.WriteLine(lstObj.ElementAt(middleindex));

      }

      public void PrintLLinkedList(LinkedLst lst)
      {
          Node newNOde = lst.head;

          while (newNOde != null)
          {
              Console.WriteLine(newNOde.data);
              newNOde = newNOde.nxt;
          }
         // Console.WriteLine(lst.head.data);
      }


    }
}

No comments:

Post a Comment