Oracle Interview Question
Software Engineer / DevelopersCountry: -
Interview Type: In-Person
public static void deleteMe(LNode me){
if(me.next == null) return; // If it is the last element of the list, this cannot be deleted
if(me.next.next == null){
me.value = me.next.value;
me.next = null;
}else{
while(me.next.next != null){
me.value = me.next.value;
me = me.next;
}
me.next = null;
}
}
By knowing that the node to be removed is in the middle of the linked list we can deduce that there is another node after the current node (which we want to remove). So instead of removing the current node, we'll just set its data to the data of the next node and remove the next node (by setting the next of the current node to the next of the next node).
Complexity: O(1) run-time.
- IvgenyNovo January 28, 2014