How to find nth element from the end of a singly linked list?

后端 未结 28 1171
感动是毒
感动是毒 2020-12-04 06:08

The following function is trying to find the nth to last element of a singly linked list.

For example:

If the elements are

28条回答
  •  没有蜡笔的小新
    2020-12-04 06:27

    Solution in C#. Create a LinkedList with dummy values.

      LinkedList ll = new LinkedList();
                ll.AddFirst(10);
                ll.AddLast(12);
                ll.AddLast(2);
                ll.AddLast(8);
                ll.AddLast(9);
                ll.AddLast(22);
                ll.AddLast(17);
                ll.AddLast(19);
                ll.AddLast(20);
    

    Create 2 pointers p1 & p1 which point to the First Node.

            private static bool ReturnKthElement(LinkedList ll, int k)
            {
                LinkedListNode p1 = ll.First;
                LinkedListNode p2 = ll.First;
    

    Iterate through the loop till either p2 is null - which means linkedlist length is less than Kth element OR till the Kth element

                for (int i = 0; i < k; i++)
                {
                    p2 = p2.Next;
                    if (p2 == null)
                    {
                        Console.WriteLine($"Linkedlist is smaller than {k}th Element");
                        return false;
                    }
                }
    

    Now, iterate both the pointers till p2 is null. Value containted in p1 pointer will correspond to Kth Element

    
                while (p2 != null)
                {
                    p1 = p1.Next;
                    p2 = p2.Next;
                }
                //p1 is the Kth Element
                Console.WriteLine($"Kth element is {p1.Value}");
                return true;
            }
    

提交回复
热议问题