in DS edited by
25,577 views
85 votes
85 votes

Consider the C code fragment given below.

typedef struct node {
    int data;
    node* next;
} node;

void join(node* m, node* n) {
    node* p = n;
    while(p->next != NULL) {
        p = p->next;
    }
    p->next = m;
}

Assuming that m and n point to valid NULL-terminated linked lists, invocation of join will

  1. append list m to the end of list n for all inputs.
  2. either cause a null pointer dereference or append list m to the end of list n.
  3. cause a null pointer dereference for all inputs.
  4. append list n to the end of list m for all inputs.
in DS edited by
25.6k views

4 Comments

"Assuming that m and n point to valid NULL-terminated linked lists" – the line says  that the linked lists are not infinite they are finite ..

hence option B is correct.

0
0

@Rajatagrawal   firstly you need to have something to NULL-terminate. The statement points to the fact that the linked list will have atleast one node. (in my opinion, of course).

If $n$ is $NULL$, then it’s not even a linked list, but a just a pointer.

0
0

11 Answers

0 votes
0 votes

The correct answer is (A)

Explanation:

1. void join(node *m, node *n){

    Here we are sending pointer reference of two node type data. It is a linked list.

2. node *p = n;

    Now, new pointer node p defined with its initial value equal to n. So now, p also points to start of n.

3. while (p->next !=NULL){

    start of traversal of linked list. If the next pointer of the node is pointing to NULL then stop there.

4. p = p->next;

    If p->next is not pointing to NULL i.e. it is not end of the list then update value of p = p->next i.e. now it will be pointing to the next node.

5. }

   When the loop ends, the p will be pointing to the last node with p->next = NULL

6. p->next = m;

   p->next which was pointing to NULL now will point to m, which the start of next node.

7. }

   End of program.

So, list m will append to end of list n.

1 comment

great explaination
0
0
0 votes
0 votes
As specified in the question m & n are valid lists, but there is no specific condition/ statement tells that lists are empty or not.
So have to consider both the cases.
⇾ Case 1. Lists are not null, invocation of JOIN will append list m to the end of list n.
m = 1, 2, 3
n = 4, 5, 6
After join, it becomes 4, 5, 6, 1, 2, 3, NULL.
⇾Case 2. If lists are null, if the list n is empty, and itself NULL, then joining & referencing would obviously create a null pointer issue.
Hence, it may either cause a NULL pointer dereference or appends the list m to the end of list n.
–1 vote
–1 vote
may be possible for null pointer derefrences because m and n may point at end of list. which are null.
Answer:

Related questions