You need to remove the first element which contains a given value from a doubly linked list.
I created two solutions since I find the edge case of removing the first element to be problematic. So I solved it using 2 approaches:
- using void function and ref
- using return value
using System;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinkedListQuestions
{
//remove the first element in the list which equals to value
[TestClass]
public class DoublyLinkedListTest
{
private Node head;
[TestInitialize]
public void InitList()
{
head = new Node();
Node two = new Node();
Node three = new Node();
Node four = new Node();
head.Value = 1;
head.Next = two;
two.Value = 2;
two.Prev = head;
two.Next = three;
three.Value = 3;
three.Next = four;
three.Prev = two;
four.Value = 4;
four.Prev = three;
}
[TestMethod]
public void RemoveValueRefFromMiddleOfListTest()
{
DoublyLinkedListHelper.RemoveRefElement(ref head, 3);
Assert.AreEqual(1, head.Value);
Assert.AreEqual(2, head.Next.Value);
Assert.AreEqual(4, head.Next.Next.Value);
}
[TestMethod]
public void RemoveValueFromMiddleOfListTest()
{
head = DoublyLinkedListHelper.RemoveElement(head, 3);
Assert.AreEqual(1,head.Value);
Assert.AreEqual(2, head.Next.Value);
Assert.AreEqual(4, head.Next.Next.Value);
}
[TestMethod]
public void RemoveValueRefFromTopOfListTest()
{
DoublyLinkedListHelper.RemoveRefElement(ref head, 1);
Assert.AreEqual(2, head.Value);
Assert.AreEqual(3, head.Next.Value);
Assert.AreEqual(4, head.Next.Next.Value);
}
[TestMethod]
public void RemoveValueFromTopOfListTest()
{
head = DoublyLinkedListHelper.RemoveElement(head, 1);
Assert.AreEqual(2, head.Value);
Assert.AreEqual(3, head.Next.Value);
Assert.AreEqual(4, head.Next.Next.Value);
}
}
public class DoublyLinkedListHelper
{
public static void RemoveRefElement(ref Node head, int value)
{
if (head == null)
{
return;
}
Node curr = head;
Node prev = null;
Node next = head.Next;
while (curr != null)
{
if (curr.Value == value)
{
if (prev != null)
{
prev.Next = next;
}
if (next != null)
{
next.Prev = prev;
}
curr.Next = null;
curr.Prev = null;
if (curr == head)
{
head = next;
}
break;
}
prev = curr;
curr = next;
next = curr.Next;
}
}
public static Node RemoveElement(Node head, int value)
{
if (head == null)
{
return null;
}
Node curr = head;
Node prev = null;
Node next = head.Next;
while (curr != null)
{
if (curr.Value == value)
{
if (prev != null)
{
prev.Next = next;
}
if (next != null)
{
next.Prev = prev;
}
curr.Next = null;
curr.Prev = null;
if (curr == head)
{
return next;
}
else
{
return head;
}
break;
}
prev = curr;
curr = next;
next = curr.Next;
}
return head;
}
}
public class Node
{
public int Value { get; set; }
public Node Prev { get; set; }
public Node Next { get; set; }
}
}