You must Sign In to post a response.
  • Category: .NET

    Get the 5 th element from end of linked list

    write a program in c# to get 5 th element from end of singular linked list
  • #765663
    it is simple, The ElementAt extension method will do it, Use 'Count ' property of linkedlist to get the total number of items in the list and the get the specific location item
    see below snippet

    int iCount = linkedList.Count;
    var value = linkedList.ElementAt(iCount - 5);

    hope it helps

    Thanks
    Koolprasd2003
    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]

  • #766317
    hi
    try this code


    List<string> lststr = new List<string>();
    lststr.Add("A");
    lststr.Add("B");
    lststr.Add("C");
    lststr.Add("D");
    lststr.Add("E");
    lststr.Add("F");
    lststr.Add("G");
    lststr.Add("H");

    for (int i = 0; i <= lststr.Count - 1; i++)
    {
    if (i == 5)
    {
    //Statement
    }
    }

    Name : Dotnet Developer-2015
    Email Id :kumaraspcode2009@gmail.com

    'Not by might nor by power, but by my Spirit,' says the LORD Almighty.

  • #766328
    Hi,
    Please find an algorithm written in C# to find nth element from end of linked list:
    http://www.c-sharpcorner.com/uploadfile/rawatgaurav/find-nth-element-from-last-in-a-linked-list/

  • #766348
    simply you need to Loop throw index times and find the element

    public SLElement Remove(int index)
    {
    SLElement prev = _root;
    if(prev == null) return null; //or throw exception
    SLElement curr = _root.next;
    for(int i = 1; i < index; i++)
    {
    if(curr == null) return null; //or throw exception
    prev = curr;
    curr = curr.next;
    }
    prev.next = curr.next; //set the previous's node point to current's next node
    curr.next = null;
    return curr;
    }

    Thanks
    Koolprasd2003
    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]


Sign In to post your comments