Mark As Completed Discussion

To insert an element into a sorted linked list while maintaining the order, we need to find the correct position for the new element based on its value. We can then insert the new element at that position.

Here's the C++ code for implementing the insertion in a sorted linked list:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4// Linked List Node
5class Node {
6public:
7    int data;
8    Node* next;
9
10    Node(int value) {
11        data = value;
12        next = nullptr;
13    }
14};
15
16// Linked List Class
17class LinkedList {
18public:
19    Node* head;
20
21    LinkedList() {
22        head = nullptr;
23    }
24
25    // Insertion in a Sorted Linked List
26    void insertSorted(int value) {
27        Node* newNode = new Node(value);
28        if (head == nullptr || value < head->data) {
29            newNode->next = head;
30            head = newNode;
31        } else {
32            Node* current = head;
33            while (current->next != nullptr && current->next->data < value) {
34                current = current->next;
35            }
36            newNode->next = current->next;
37            current->next = newNode;
38        }
39    }
40};
41
42int main() {
43    // Create a Linked List
44    LinkedList list;
45    list.insertSorted(3);
46    list.insertSorted(1);
47    list.insertSorted(2);
48
49    // Print the Linked List
50    Node* current = list.head;
51    while (current != nullptr) {
52        cout << current->data << " ";
53        current = current->next;
54    }
55    cout << endl;
56
57    return 0;
58}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment