What is wrong with the following definition of headInsert st

What is wrong with the following definition of headInsert?

struct Node {

int item;

Node* link; };

typedef Node* NodePtr;

void headInsert(NodePtr& head, int data) {

NodePtr tmp = new Node;

tmp->item = data;

head->next = tmp;

tmp->next = head->next;

}

NodePtr head; headInsert(head, 4);

A. tmp should be declared to be a Node not a NodePtr.

B. head->next is pointing to NULL.

C. Nothing is wrong.

D. If there were any nodes following head they are now lost.

Solution

B. head->next is pointing to NULL.
Because of which tmp is not getting stored in the linked list


Correct Code:
struct Node
{
   int item;
   Node* link;
};

typedef Node* NodePtr;

void headInsert(NodePtr& head, int data)
{
   NodePtr tmp = new Node;
   tmp->item = data;

   // next of tmp should be assigned head
   tmp->link = head;
   head = tmp;
}

What is wrong with the following definition of headInsert? struct Node { int item; Node* link; }; typedef Node* NodePtr; void headInsert(NodePtr& head, int

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site