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

后端 未结 28 1086
感动是毒
感动是毒 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:36

    Here is C# version of finding nth child from Linklist.

    public Node GetNthLast(Node head, int n)
        {
            Node current, nth;
            current = nth = head;
            int counter = 0;
    
            while (current.next != null)
            {
                counter++;
                if (counter % n == 0)
                {
                    for (var i = 0; i < n - 1; i++)
                    {
                        nth = nth.next;
                    }
                }
                current = current.next;
            }
            var remainingCounts = counter % n;
            for (var i = 0; i < remainingCounts; i++)
            {
                nth = nth.next;
            }
            return nth;
        }
    

提交回复
热议问题