Thursday, September 3, 2020

Given a linked list, remove the n-th node from the end of list.

Note: Condition was given that n will always be valid.

Approach: Use two pointers.

Implementation in C#:

        public void RemoveNthFromEnd(int n)

        {

            LinkedListNode first = this.Head, second = this.Head;

            for (int i = 1; i <= n; ++i)

            {

                second = second.Next;

                if (second == null)

                {

                    this.Head = this.Head.Next;

                    return;

                }

            }

            while (second.Next != null)

            {

                first = first.Next;

                second = second.Next;

            }

            first.Next = first.Next.Next;

        }

Complexity: O(n)

No comments:

Post a Comment