NVIDIA Interview Question
Software Engineer / Developerscan't we just set free(lastnode) if the node is last? what is the problem in that? It works fine.
what is the pointer given wasn't the pointer from the previous node , it was some random pointer(we don't have the luxury to directly set the given pointer to NULL or set it to node next to the one that gets deleted )
I am sorry, if it is last node you cannot delete it as you don't have any access to previous pointers as well as the nest pointers. Also, you cannot make a node null as it did out of mistake.
Sorry about that!
Normally, in a singly linked list problem, we have access to header of the list. So for the problem in hand, if we have the pointer to the node to be deleted and the HEADER, we can delete the last node as well.
//code snippet:
node p=header;
while(p.next!= pointerToNodeToBeDeleted)
{
p=p.next;
}
p.next=null;
Although we have virtually deleted the node....we have not yet freed the node from the memory.
what about freeing the node?is it possible to free it or no?
void deletenode(struct node* nodetobeDeleted) {
struct node* temp = nodetobeDeleted->next;
nodetobeDeleted->data = temp->data;
nodetobeDeleted->next = temp->next;
free temp;
}
We cannot delete the last node without making use of head pointer.
if ( node->next! = NULL) { // check if the node is not the last node
while(node->next!=NULL){
node->value = node->next->value;
if(node->next->next == NULL) {// check if the node is the second last node
free(node->next); // always free the last node after adjusting node-> value
node->next = NULL;
break;
}
node= node->next
}
}else { // if the node is the last node
NODE * temp;
temp = node;
node =NULL;
free(temp);
}
I assume that it is a singly linked list. So what we can do is since we have the pointer to the node which we have to remove, we can copy the data of the next node into the present node and increment the pointer and remove that node. If the next node is null then just remove the present node.
public void deleteNode( Node currentNode)
- Miss N April 15, 2011{
if(currentNode.next==null)
{
/*This means we are on the last node, if we make this node null, so the previous node that points to it
* we get null in the next pointer. This way this node will be removed from the list
*/
currentNode=null;
}
else
{
/*all we know about a the current node is its value and the next pointer
so if we can update the value of the node then we have overridden the value of
the node we wanted to delete*/
// step 1:
current.value= current.next.value;
/*now we need to update the pointer, since we already got the value of next node in out current node, we don't need that node.
But, we sure want to remove it from the list. So, we will update the current node's next pointer to the next node's
next pointer thereby removing the next node
*/
// step 2:
current.next= current.next.next;
}
}