Given a sorted singly linked list and a data, your task is to insert the data in the linked list in a sorted way i.e. order of the list doesn't change.
Copy Input:
LinkedList: 25->36->47->58->69->80
data: 19
Output: 19 25 36 47 58 69 80
Copy Input:
LinkedList: 50->100
data: 75
Output: 50 75 100
Copy Node *sortedInsert(struct Node *head, int data)
{
Node *p = head;
Node *q = NULL;
Node *temp = new Node(data);
while (p != NULL)
{
if (data < p->data)
{
if (q == NULL)
{
temp->next = head;
head = temp;
}
else
{
temp->next = p;
q->next = temp;
}
return head;
}
q = p;
p = p->next;
}
if(p == NULL){
q->next = temp;
}
return head;
}