793 views
5 votes
5 votes

Given the following declaration:

Node declaration:

struct LLNode{
    int data;
    struct LLNode *next;
    }
    typedef struct LLNode Node;


following are the functions to insert a node at start of Linked List. Assume "head"is pointer to first Node of the Linked List.
"Head_ref" is a pointer to "head".

Implementation A

void insert(Node *head,int data)
    {
        Node *NewNode= (Node *)malloc(sizeof(Node));
        NewNode->data=data;
        NewNode->next=head;
        head=NewNode;
    }

Implementation B

void insert(Node **head_ref,int data)
    {
        Node *NewNode= (Node *)malloc(sizeof(Node));
        NewNode->data=data;
        NewNode->next=*(head_ref);
        *(head_ref)=NewNode;
    }

Which Of the following is correct Implementation

A)ONLY A

B)ONLY B

C)both

D)None

1 Answer

Best answer
8 votes
8 votes

Only implementation B is correct ; the reason being in insertion at the beginning of the linked list , the head node will change..So head pointer gets manipulated..Hence we pass the address of head pointer instead so that we can manipulate the head pointer..

In operations where head pointer need not be changed like printing or traversing linked list , there we can pass the head pointer itself in the argument of the concerned function.

Hence B) should be the correct answer..

selected by

Related questions

0 votes
0 votes
1 answer
4
Souvik33 asked Nov 2, 2022
865 views
Which data structure would be most appropriate to implement a collection of values with the following 3 characteristicsSingly link list with head and tail pointerDoubly l...