﻿ C++ - Find middle element in a single linked list

# C++ Linked List Exercises: Find middle element in a single linked list

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

Write a C++ program to find the middle element of a given Linked List.

Test Data:
Original list:
9 7 5 3 1
Middle element of the said list:
5
Original list:
7 5 3 1
Middle element of the said list:
3
Explanation: The second node of the list is returned since it has the values 5 and 3.

Sample Solution:

C++ Code:

``````#include <iostream>

using namespace std;

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

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

{
int c = 0;
if(c%2 != 0) middle = middle->next;
c++;
}
return middle->num;
}

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

int main()
{

cout << "Original list:\n";
cout << "\nMiddle element of the said list:";
cout << "\n" << get_Middle(head) << "\n";
cout << "\nOriginal list:\n";
cout << "\nMiddle element of the said list:";
cout<<endl;
return 0;
}
``````

Sample Output:

```Original list:
7 5 3 1
Middle element of the said list:
3

Original list:
9 7 5 3 1
Middle element of the said list:
5
```

Flowchart:

CPP Code Editor:

Previous C++ Exercise: Insert a new node at the end of a Linked List.
Next C++ Exercise: Insert new node at the middle of 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