# 1. Introduction

This blog post delves into a common problem in linked list manipulation: inserting a new node into a sorted linked list in its correct position. The challenge is to maintain the sorted order of the list after the insertion.

## Problem

Given a sorted singly linked list in increasing order and a single node, the task is to insert the node into the list such that the list remains sorted.

Examples:

- Input: List = 2 —> 4 —> 6 —> 8 —> nullptr, Node = 9

Output: 2 —> 4 —> 6 —> 8 —> 9 —> nullptr

- Input: List = 2 —> 4 —> 6 —> 8 —> nullptr, Node = 1

Output: 1 —> 2 —> 4 —> 6 —> 8 —> nullptr

- Input: List = 1 —> 2 —> 4 —> 6 —> 8 —> 9 —> nullptr, Node = 5

Output: 1 —> 2 —> 4 —> 5 —> 6 —> 8 —> 9 —> nullptr

# 2. Solution Steps

1. Define a ListNode structure for the linked list.

2. Create a function to insert a new node in the sorted list.

3. In the function, handle edge cases such as an empty list or insertion at the beginning.

4. Traverse the list to find the correct insertion point.

5. Insert the new node and update the pointers.

# 3. Code Program

``````#include <iostream>
using namespace std;

// Define the ListNode structure
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};

// Function to insert a new node in a sorted linked list
ListNode* sortedInsert(ListNode* head, ListNode* newNode) {
return newNode;
}

while (current->next != nullptr && current->next->val < newNode->val) {
current = current->next;
}

newNode->next = current->next;
current->next = newNode;
}

// Function to print the linked list
cout << head->val << " —> ";
}
cout << "nullptr\n";
}

int main() {
// Creating a sorted linked list

// Inserting a new node
ListNode* newNode = new ListNode(5);

return 0;
}
``````

### Output:

```2 —> 4 —> 5 —> 6 —> 8 —> nullptr
```

### Explanation:

The sortedInsert function inserts a new node into a sorted linked list while maintaining the list's sorted order. It first checks if the new node should be inserted at the beginning of the list. If not, it traverses the list to find the correct insertion point, updates the pointers accordingly, and returns the head of the modified list. The main function demonstrates this by creating a sorted list, inserting a new node, and then printing the updated list.