To find the middle element of a linked list, we can use the slow and fast pointer approach. The slow pointer moves one node at a time, while the fast pointer moves two nodes at a time. By the time the fast pointer reaches the end of the list, the slow pointer will be at the middle element.
Here's an example C++ code to find the middle element of a linked list:
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4// Linked List Node
5struct Node {
6 int data;
7 Node* next;
8 Node(int d) : data(d), next(nullptr) {}
9};
10
11// Function to find the middle element of a linked list
12Node* findMiddle(Node* head) {
13 if (head == nullptr) {
14 return nullptr;
15 }
16
17 Node* slow = head;
18 Node* fast = head;
19
20 while (fast != nullptr && fast->next != nullptr) {
21 slow = slow->next;
22 fast = fast->next->next;
23 }
24
25 return slow;
26}
27
28int main() {
29 // Create a linked list
30 Node* head = new Node(1);
31 head->next = new Node(2);
32 head->next->next = new Node(3);
33 head->next->next->next = new Node(4);
34 head->next->next->next->next = new Node(5);
35
36 // Find the middle element
37 Node* middle = findMiddle(head);
38
39 if (middle != nullptr) {
40 cout << "The middle element is: " << middle->data << endl;
41 } else {
42 cout << "The list is empty." << endl;
43 }
44
45 return 0;
46}xxxxxxxxxx46
}using namespace std;// Linked List Nodestruct Node { int data; Node* next; Node(int d) : data(d), next(nullptr) {}};// Function to find the middle element of a linked listNode* findMiddle(Node* head) { if (head == nullptr) { return nullptr; } Node* slow = head; Node* fast = head; while (fast != nullptr && fast->next != nullptr) { slow = slow->next; fast = fast->next->next; } return slow;}int main() { // Create a linked listOUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment



