﻿ C++ - Reverse linked list

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

Write a C++ program to create a singly linked list of n nodes and display it in reverse order.

Visualization:

Test Data:
11 9 7 5 3 1
1 3 5 7 9 11

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 reverse()
{
// Set the current, previous, and next pointers to their initial values
node *prev = NULL, *next = NULL;

while (current != NULL) {
// Store next
next = current->next;
// Reverse the node pointer for the current node
current->next = prev;
// Advance the pointer one position.
prev = current;
current = next;
}
}
//Display all nodes
void display_all_nodes()
{
while(temp!=NULL){
cout<<temp->num<<" ";
temp=temp->next;
}
cout<<endl;
}

int main(){
insert_Node(1);
insert_Node(3);
insert_Node(5);
insert_Node(7);
insert_Node(9);
insert_Node(11);
display_all_nodes();
reverse();
display_all_nodes();
return 0;
}
``````

Sample Output:

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

1 3 5 7 9 11
```

Flowchart:

CPP Code Editor:

Previous C++ Exercise: Create and display linked list.
Next C++ Exercise: Count number of nodes in 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