Example:
Input: 1->2->1->2->1, val = 1 Output: 2->2
Approach: Not much to discuss here. It is a straight forward solution. We just need to remember that to delete a node from Linked List, we need to have reference to previous node.
Implementation in C#:
public void RemoveElements(int val)
{
if (this.Head == null)
{
return;
}
LinkedListNode dummyNode = new LinkedListNode(-1, this.Head);
LinkedListNode currNode = dummyNode;
while(currNode.Next != null)
{
if (currNode.Next.Value == val)
{
currNode.Next = currNode.Next.Next;
}
else
{
currNode = currNode.Next;
}
}
this.Head = dummyNode.Next;
}
Complexity: O(n)
No comments:
Post a Comment