# Find middle of singly linked list Recursively in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Consider we have a list of numbers; our task is to find the middle of the linked list using recursion. So if the list elements are [12, 14, 18, 36, 96, 25, 62], then the middle element is 36.

To solve this problem, we will count total number of nodes in the list in recursive manner and do half of this. Then rolling back through recursion decrement n by 1 in each call, return element where n is zero.

## Example

#include<iostream>
#include<stack>
using namespace std;
class Node{
public:
int data;
Node *next;
};
Node* getNode(int data){
Node *newNode = new Node;
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void midpoint_task(Node* head, int* n, Node** mid){
if (head == NULL) {
*n /= 2;
return;
}
*n += 1;
*n -= 1;
if (*n == 0) {
}
}
Node* findMidpoint(Node* head) {
Node* mid = NULL;
int n = 1;
return mid;
}
void append(struct Node** start, int key) {
Node* new_node = getNode(key);
Node *p = (*start);
if(p == NULL){
(*start) = new_node;
return;
}
while(p->next != NULL){
p = p->next;
}
p->next = new_node;
}
int main() {
Node *start = NULL;
int arr[] = {12, 14, 18, 36, 96, 25, 62};
int size = sizeof(arr)/sizeof(arr);
for(int i = 0; i<size; i++){
append(&start, arr[i]);
}
Node* res = findMidpoint(start);
cout << "Mid point is: " << res->data;
}

## Output

Mid point is: 36