
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements