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

后端 未结 28 1161
感动是毒
感动是毒 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条回答
  •  旧时难觅i
    2020-12-04 06:29

    Just another solution to this problem. Though the time complexity remains the same, this code achieves the solution in a single loop.

    public Link findKthElementFromEnd(MyLinkedList linkedList, int k)
        {
            Link current = linkedList.getFirst();//current node
            Link currentK = linkedList.getFirst();//node at index k
    
            int counter = 0;
    
            while(current.getNext()!=null)
            {
                counter++;
    
                if(counter>=k)
                {
                    currentK = currentK.getNext();
                }
    
                current = current.getNext();
            }
    
            //reached end
            return currentK;
        }
    

提交回复
热议问题