in DS recategorized by
371 views
8 votes
8 votes

Consider the following program. printlist() is a function that takes the head of a linked list and prints all nodes values separated by comma. Node is typedefed singly linked list type struct.

void insert1(Node *head,int data)
{
    Node *NewNode= (Node *)malloc(sizeof(Node));
    NewNode->value=data;
    NewNode->next=head;
    head=NewNode;
}
void insert2(Node **head_ref,int data)
{
    Node *NewNode= (Node *)malloc(sizeof(Node));
    NewNode->value=data;
    NewNode->next=*(head_ref);
    *(head_ref)=NewNode;
}
int main()
{
    /* create a linked list 1->2->3->4->5 
and head points to the first node.*/
    insert1(head,9);
    printlist(head); //Line X

    //The list is restored to its initial state

    insert2(&head,9);
    printlist(head); //Line Y
}

Which of the following is/are true about the above program?

  1. Line $\text{X}$ prints $9,1,2,3,4,5$
  2. Line $\text{Y}$ prints $9,1,2,3,4,5$
  3. Line $\text{X}$ prints $1,2,3,4,5$
  4. Line $\text{Y}$ prints $1,2,3,4,5$
in DS recategorized by
371 views

2 Comments

@GO Classes @Mittal sachin Sir had the printList function been called within insert1(), after the 4 line. It should have printed the 9 1 2 3 4 5? Is it not sir?

  1. void insert1(Node *head,int data)
  2. {
  3. Node *NewNode= (Node *)malloc(sizeof(Node));
  4. NewNode->value=data;
  5. NewNode->next=head;
  6. head=NewNode;
  7. printList(head); // it should print 9 1 2 3 4 5
  8. }
0
0

Because of 2 concepts : 

1.) CALL BY VALUE : 

2.) CALL BY REFERENCE : 

 

X: After insert1() memory is in heap: with no reference to given to outside world, hence “MEMORY LEAK”

Y: Same as that of X but in this case reference of head changes, the head act as a pointer to memory created inside function even after it(function) gets destroyed.

 

0
0

1 Answer

16 votes
16 votes
Best answer

Answers are option B and option C

selected by
Answer:

Related questions