
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find middle of singly linked list Recursively in C++
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; midpoint_task(head->next, n, mid); *n -= 1; if (*n == 0) { *mid = head; } } Node* findMidpoint(Node* head) { Node* mid = NULL; int n = 1; midpoint_task(head, &n, &mid); 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[0]); 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
- Related Articles
- Program to find the middle node of a singly linked list in Python
- Convert singly linked list into circular linked list in C++
- Convert singly linked list into XOR linked list in C++
- Difference between Singly linked list and Doubly linked list in Java
- Delete middle of linked list in C++?
- Singly Linked List as Circular in Javascript
- Find the common nodes in two singly linked list in C++
- Find smallest and largest elements in singly linked list in C++
- Product of the nodes of a Singly Linked List
- Delete middle of linked list in C++ program
- Binary Search on Singly Linked List in C++
- Remove elements from singly linked list in JavaScript
- Find minimum and maximum elements in singly Circular Linked List in C++
- C++ Program to Implement Singly Linked List
- JavaScript: How to Find the Middle Element of a Linked List?

Advertisements