edited by
25,395 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.
edited by

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.

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 votes
–1 votes
may be possible for null pointer derefrences because m and n may point at end of list. which are null.
Answer:

Related questions

38 votes
38 votes
7 answers
1
Arjun asked Feb 14, 2017
18,661 views
Let $T$ be a tree with $10$ vertices. The sum of the degrees of all the vertices in $T$ is ________
33 votes
33 votes
10 answers
2
Arjun asked Feb 14, 2017
16,620 views
Let $T$ be a binary search tree with $15$ nodes. The minimum and maximum possible heights of $T$ are:Note: The height of a tree with a single node is $0$.$4$ and $15$ res...