﻿ C++ - Insert new node at the middle of a Singly Linked List

# C++ Linked List Exercises: Insert new node at the middle of a Singly Linked List

## C++ Linked List: Exercise-7 with Solution

Write a C++ program to insert a new node at the middle of a given Singly Linked List.

Test Data:
Original list:
7 5 3 1
Singly Linked List: after insert 9 in the middle of the said list-
7 5 9 3 1
Singly Linked List: after insert 11 in the middle of the said list-
7 5 9 11 3 1
Singly Linked List: after insert 13 in the middle of the said list-
7 5 9 13 11 3 1

Sample Solution:

C++ Code:

``````#include <iostream>

using namespace std;

struct  Node
{
int data;
Node *next;
};

int size = 0;
Node* new_Node = new Node();
new_Node->data = data;
size++;
}

Node* new_Node = new Node();
new_Node->data = data;
new_Node->data = data;
size++;
return;
}

// Find insertion position for middle
int mid = (size % 2 == 0) ? (size/2) : (size+1)/2;
while(--mid){
temp = temp->next;
}
new_Node->next = temp->next;
temp->next = new_Node;
size++;

}

//Display all nodes
void display_all_nodes(Node* node)
{
while(node!=NULL){
cout << node->data << " ";
node = node->next;
}
}

int main()
{

cout << "Original list:\n";
cout << "\nSingly Linked List: after insert 9 in the middle of the said list-\n";
cout << "\nSingly Linked List: after insert 11 in the middle of the said list-\n";
cout << "\nSingly Linked List: after insert 13 in the middle of the said list-\n";
cout<<endl;
return 0;

}
``````

Sample Output:

```Original list:
7 5 3 1
Singly Linked List: after insert 9 in the middle of the said list-
7 5 9 3 1
Singly Linked List: after insert 11 in the middle of the said list-
7 5 9 11 3 1
Singly Linked List: after insert 13 in the middle of the said list-
7 5 9 13 11 3 1
```

Flowchart:

CPP Code Editor:

Previous C++ Exercise: Find middle element in a single linked list.
Next C++ Exercise: Get Nth node in a Singly Linked List.

What is the difficulty level of this exercise?

﻿

## C++ Programming: Tips of the Day

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

```#include <algorithm>
#include <string>

void some_func() {
std::string s = "example string";
std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}
```

Ref: https://bit.ly/3niU71x