Implement insertion of node in sorted linked list in C++

Code


#include <iostream>

using namespace std;

class Node
{
public:
int data;
Node *next;
};

void insertsorted(Node **head, int data)
{
Node *newnode = new Node();
newnode->data = data;
newnode->next = NULL;
if (*head == NULL)
{
*head = newnode;
return;
}
Node *current = *head;
if (current->data > data)
{
newnode->next = current;
*head = newnode;
return;
}
while (current->next != NULL && current->next->data < data)
{
current = current->next;
}
newnode->next = current->next;
current->next = newnode;
}

void printlist(Node *head)
{
while (head != NULL)
{
cout << head->data << " ";
head = head->next;
}
}

int main()
{
Node *head = NULL;
insertsorted(&head, 4);
insertsorted(&head, 1);
insertsorted(&head, 5);
insertsorted(&head, 3);
insertsorted(&head, 2);

printlist(head);

}

Output

1 2 3 4 5