Adobe Interview Question
Computer ScientistsCountry: India
Interview Type: In-Person
consider this example:
1->2->3->4
and x is 2
you code does this:
1->3->3->4 (node->data = node->next->data;)
1->3->4 (node->next = node->next->next;)
1->3(delete node.next)// this particular line is not required according to me.
Thanks Shreyas. I should have saved the node->next to a temp and delete it at the end. Deleting node->next is definitly a bug.
we can remove the limitation of not deleting the last node by adding this :-
if(node->next == NULL)
{
free(node);
node = NULL;
}
Am I correct?
In above answer, how will you update an arbitrary "previous" element's ->next pointer to your "node->next" value?
Wont work. List gets broken.
Must have a doubly linked list; then its trivial.
Small correction in last line
node.next = temp.next
Since we are copying everything to the current node and deleting next node..
Small correction in last line
node.next = temp.next
Since we are copying everything to the current node and deleting next node..
Idea is very well known and It can be done in Constant time ,Having One limitation(If last node is passed)..Please have the following code snippet..
void delete(struct node *x)
{
struct node *y=NULL;
y=x->next;
x->data=y->data;
x->next=y->next;
free(y);
}
If you find any mistake then please let us know.
I'm surprised that none of you have mentioned how you'll move forward as well as backward of any arbitrarily given node!!
To me the catch is to assume that the list be either a doubly linked list or a circular list so that given any arbitrary node, you can traverse through all nodes.
Once any one of these assumptions is considered, rest of the solution is trivial.
void Adrs_of_node_to_be_deleted(NODE *node)
{
if(node->next == NULL)
{
printf("You are trying to delete last Node which is not possible as you should know previous node adrs to make it point to null after deleting last node..\n");
return;
}
while(node->next != NULL)
{
node->data = node->next->data;
if(node->next->next==NULL)
{
free(node->next);
node->next = NULL;
return;
}
node->next = node->next->next;
node = node->next;
}
return;
}
Its really simple:
what you have to do is:
1) take the next node's value in this node.
2) delete the next node.
if the given node is the last node then handle separately.
code using java.
public void delNode(Node curr)
{
if(curr.next==null)
{
curr=null; // in case curr is last
return;
}
curr.info=curr.next.info;
curr.next=curr.next.next;
}
Limitation: Cannot delete the last node.
- Ric February 21, 2012