Wednesday, July 29, 2015

Linked List: Find nth element from end.

Find nth element from the end of the linked list.

Note: Use linked list created in this blog page: Singly Linked List

Logic:
Here we have two pointers in linked list, root pointer (tempRoot) and nth node pointer (tempNth), tempRoot pointer keeps on traversing linked list till we have a difference of n nodes between Head and tempRoot. Then assign head to tempNth so that we have difference of n nodes between tempRoot and tempNth. Now, keep on traversing linked list, by incrementing both pointers, till we reach end of linked list. At the end our tempNth pointer will be pointing to nth element from end.
   

        public T Find_nth_fromEnd(int pIndex)
        {
            T returnValue = default(T);
            int counter = pIndex;


            // We have pointer to head of linked list.
            Node tempRoot = this.Head;  
            Node tempNth;

            while (counter > 1)
            {
                tempRoot = tempRoot.next;

                if (tempRoot == null)
                {
                    return returnValue;
                }

                counter--;
            }

            tempNth = this.Head;

            while (tempRoot.next != null)
            {
                tempNth = tempNth.next;
                tempRoot = tempRoot.next;
            }

            return tempNth.content;
        }


No comments:

Post a Comment