• RSS
  • Facebook
  • Twitter

Knowledge is Power.

  • Who you are ?

    Working on machines without understanding them ? Then you should be here..

  • Where you are ?

    Geographical location should not become a barrier to Share our knowledge.

  • What do you do ?

    Puzzles and Interview question are intended to be discussed here.

    Wednesday, June 30, 2010

    Given a pointer to a node in a singly linked list, how do you delete the node ?
    A simple solution is to traverse the linked list until you find the node you want to delete. But this solution requires pointer to the head node which contradicts the problem statement.
    Fast solution is to copy the data from the next node to the node to be deleted and delete the next node. Something like following.
        struct node *temp  = node_ptr->next;
       node_ptr->data  = temp->data;
       node_ptr->next  = temp->next;
       free(temp);
    In java, the code would look something like this :
    1public void deleteNode(Node node){
    2 Node temp = node.next;
    3 node.data = temp.data;
    4 node.next = temp.next;
    5 //do nothing with temp and let the garbage collector remove it
    6 }

    0 comments:

    Post a Comment