retagged by
363 views
2 votes
2 votes

Consider the linked list initially having values $1, 2, 2, 8, 6, 2, 2,$ and let the head be the pointer to the first node of the linked list.
Which of the following options correctly represents the final linked list after the function call $\textsf{mystery(head, 2)}?$

typedef struct node {
    int value;
    struct node *next;
} Node;
Node* mystery(Node* head, int x) {
    if (head == NULL) 
        return NULL;
    
    if (head → value == x) {
        Node* tmp = head → next;
        free(head);
        return tmp;
    } else {
        head → next = mystery(head → next, x);
        return head;
    }
}
  1. Final LinkedList will be $1, 2, 8, 6, 2, 2$
  2. Final LinkedList will be $1, 8, 6$
  3. Final LinkedList will be $1, 8, 6, 2, 2$
  4. None of the above
retagged by

1 Answer

2 votes
2 votes

Initial:

Function call $\textsf{mystery(head, 2)}$ executed:
As first two $\textsf{if}$ condition will be $\textsf{FALSE}.$ So, $else$ part executed:

Now, $\textsf{mystery(head→ next, 2)}$ executed:
Second $\textsf{if}$ condition matched, so it will be executed:

Finally, after execution and returning $\textsf{head}$ Final LinkedList look like this:

$\color{Green}\textsf{Ans: A}$

Answer:

Related questions

6 votes
6 votes
0 answers
1