# Insert Node in the Sorted Linked List

Insert Node in the Sorted Linked List” is one of the popular programming problem based on Linked List data structure. Here, we are given a sorted linked list and our task is to insert a node in a sorted linked list in such a way that after inserting the new node the linked list remains sorted.

Example:

```Suppose we need to insert a node with value ‘17’ in a following linked list:
12 -> 13 -> 16 -> 19 -> 23
After Inserting in the sorted manner the linked list would be as follows:
12 -> 13 -> 16 -> 17 -> 19 -> 23```

The steps required to insert node in the sorted linked list are as follows:

1. If the linked list is empty, then the new_node will become head of the linked list.
2. Else, if the new_node value is smaller than or equal to the head node value, then point the pointer of new_node to the head of the linked list and make head of the resultant linked list to the new_node of the list.
3. Else, traverse the linked list till we get the node value greater than or equal to the new_node value.
4. Then, insert the new_node at the desired location after manipulating pointers of the linked list.

#### C++ Program to insert node in the sorted linked listis as follows:

```/* C++ Program to Insert Node in the Sorted Linked List */
#include<bits/stdc++.h>
using namespace std;

/* Structure of the Linked List */
typedef struct node
{
int data;
struct node *next;
}Node;

/* Function to Insert Node at the Sorted Linked List */
{
/* Creating New Node */
Node *new_node = (struct node*)malloc(sizeof(struct node));
new_node -> data = ele;
new_node -> next = NULL;

/* Check whether Linked List is Empty or Not */

/* If Linked List is Empty, then new node will become head of the Linked List */
{
return;
}

/* If Linked List is not empty,
1. If New Node Value is smaller or equal to Head Node Value,
then, insert new node at the beginning of the linked List

2. Else, traverse the linked list, till we get the node value
greater than or equal to the new node value. Then, insert the
new node at the desired location after manipulating pointers of
*/
{
return;
}
while(temp->next!= NULL && temp->next->data < ele)
{
temp = temp -> next;
}
new_node -> next = temp -> next;
temp -> next = new_node;
}

/* Function to print the Linked List */
{
while(temp != NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
int main()
{
/* Inserting Some Nodes in a sorted Linked List */
```OUTPUT: