Friday, January 21, 2011

Insert node in the middle of linked list


void insertMiddleNode(NODE *head, NODE *new_node) {

    if( head == NULL || new_node == NULL )
        return; 
        
    NODE *fast, *slow;
    fast = slow = head; 
    
    // move fast 2 positions

    while (fast && (fast = fast->next) && (fast = fast->next)) {
        //move slow one position
        slow = slow->next;
    }

    // now slow is middle node
    new_node->next = slow->next;
    slow->next = new_node;
}

3 comments :

  1. thanks this is first problem which i understand in a short time.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete