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

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

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

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

Visualization:

Test Data:
13 11 9 7 5 3 1
Insert a new node at the beginning of a Singly Linked List:
0 13 11 9 7 5 3 1

Sample Solution:

C++ Code:

``````#include <iostream>

using namespace std;

//Declare node
struct Node{
int num;
Node *next;
};

//Insert node at start
void insert_Node(int n){
struct Node *new_node=new Node;
new_node->num=n;
}

void NodeInsertatBegin(int new_element) {

// Create a new node
Node* new_Node = new Node();
new_Node->num = new_element;
}

//Display all nodes
void display_all_nodes()
{
while(temp!=NULL){
cout<<temp->num<<" ";
temp=temp->next;
}
}

int main(){
insert_Node(1);
insert_Node(3);
insert_Node(5);
insert_Node(7);
insert_Node(9);
insert_Node(11);
insert_Node(13);
display_all_nodes();
cout<<"\n\nInsert a new node at the beginning of a Singly Linked List:\n";
NodeInsertatBegin(0);
display_all_nodes();
cout<<endl;
return 0;
}
``````

Sample Output:

```Original Linked list:
13 11 9 7 5 3 1

Insert a new node at the beginning of a Singly Linked List:
0 13 11 9 7 5 3 1
```

Flowchart:

CPP Code Editor:

Previous C++ Exercise: Count number of nodes in a linked list.
Next C++ Exercise: Insert a new node at the end of a 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