Microsoft Interview Question
Software Engineer in TestsCountry: United States
Interview Type: In-Person
public int deleteNode(LinkedListNode head, LinkedListNode n)
{
if( n == null) return -1;
else
{
LinkedListNode current = head;
LinkedListNode previous = null;
while(current != null)
{
if(current.value == n.value)
{
//deletes first or middle elements, copy the node values from next node and deletes the //next node
if(current.next != null)
{
current.value = current.next.value;
current.next = current.next.next;
return 0;
}
else
{
previous.next = null;
return 0;
}
}
//store the previous here just in case if the element to be deleted is the last node
previous = current;
current = current.next; //move current to the next element
}
}
return 1;
}
public int deleteNode(LinkedListNode head, LinkedListNode n)
{
if( n == null) return -1;
else
{
LinkedListNode current = head;
LinkedListNode previous = null;
while(current != null)
{
if(current.value == n.value)
{
//deletes first or middle elements, copy the node values from next node and deletes the //next node
if(current.next != null)
{
current.value = current.next.value;
current.next = current.next.next;
return 0;
}
else
{
previous.next = null;
return 0;
}
}
//store the previous here just in case if the element to be deleted is the last node
previous = current;
current = current.next; //move current to the next element
}
}
return 1;
}
Here is an implementation in C#. head of linked list is passed by ref because head may be deleted and so it may change.
- berkaypamir November 04, 2012