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