Question: Write a function insert ( ) to insert a node to a linked list. A linked list contains a series of nodes and each node

Write a function insert() to insert a node to a linked list. A linked list contains a series of nodes and each node holds a value and the values. Each node contains a pointer used to link to the next node. The values in the linked list are in a sorted order. The function insert() will insert a node into the linked list in sorted fashion. A linked list starts with a pointer to the first node. If the pointer points to NULL, then it is an empty list. Complete the following program by implementing the insert()friend function. The output of the program is
01234
class Node
{
public:
Node();
Node(int val);
int getValue();
Node *getLink();
void setLink(Node &nd);
friend void insert(Node* &head, Node *nd);
friend ostream& operator <<(ostream &ost, Node *head);
private:
int value;
Node *link;
};
Node::Node() : value(0), link(NULL)
{}
Node::Node(int val) : value(val), link(NULL)
{}
Node* Node::getLink()
{
return this->link;
}
int Node::getValue()
{
return this->value;
}
void Node::setLink(Node &nd)
{
this->link = &nd;
}
void insert(Node* &head, Node *nd)
{
/* Implement insert() function */
}
ostream & operator <<(ostream &ost, Node *head)
{
Node *cur = head;
while (cur != NULL)
{
ost << cur->value;
cur = cur->link;
}
return ost;
}
int main(){
int data[5]={3,1,2,0,4};
Node *nd;
Node *head = NULL;
for (int i =0; i <5; i++)
{
nd = new Node(data[i]);
insert(head, nd);
}
cout << head << endl;
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!