Delete nodes with a given value from a doubly linked list

Delete all nodes that their values equals “foo” from a doubly linked list, your input is on of the nodes in the list

Tests:

        [TestMethod]
public void TestDeleteNodesFromDoublyLInkedList()
{
var i4 = new DoublyLinkedItem("laa", null);
var i3 = new DoublyLinkedItem("foo", i4);
i4.Previous = i3;
var i2 = new DoublyLinkedItem("laa", i3);
i3.Previous = i2;
var i1 = new DoublyLinkedItem("laa", i2);
i2.Previous = i1;
var root = new DoublyLinkedItem("foo", i1);
i1.Previous = root;

DeleteNodesFromDoublyLInkedList.Delete("foo", i2);

int counter = 1;
DoublyLinkedItem cUp = i2.Previous;
DoublyLinkedItem cDown = i2.Next;

while (cUp != null)
{
if (cUp.Value == "foo")
{
Assert.Fail("Node with value 'foo' hasn't been removed");
}
cUp = cUp.Previous;

counter++;
}

while (cDown != null)
{
if (cDown.Value == "foo")
{
Assert.Fail("Node with value 'foo' hasn't bdeen removed");
}
cDown = cDown.Next;
counter++;
}
Assert.AreEqual(3, counter);
}



Solution:

    public class DeleteNodesFromDoublyLInkedList
{
public static void Delete(string value, DoublyLinkedItem node)
{
DoublyLinkedItem cUp = node;
DoublyLinkedItem cDown = node;

while (cUp != null)
{
if (cUp.Value == value)
{
DeleteNode(cUp);
}
cUp = cUp.Previous;
}

while (cDown != null)
{
if (cDown.Value == value)
{
DeleteNode(cDown);
}
cDown = cDown.Next;
}
}

private static void DeleteNode(DoublyLinkedItem item)
{
bool root = item.Previous == null;
if (root)
{
if (item.Next == null)
{
return;
}
item.Next.Previous = null;
}
else
{
item.Previous.Next = item.Next;
}

}
}

public class DoublyLinkedItem
{
private readonly string value;

public DoublyLinkedItem(string value, DoublyLinkedItem next)
{
this.value = value;
Next = next;
}

public DoublyLinkedItem Next { get; set; }
public DoublyLinkedItem Previous { get; set; }

public string Value
{
get { return value; }
}
}

Comments