w3resource

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;
  void insert(Node** head, int num){
    Node* new_Node = new Node();
    new_Node->num = num;
    new_Node->next = *head;
    *head = new_Node;    
     size++;
}


int get_Middle(Node *head)
{
    if(!head) return -1;
    int c = 0;
    Node *middle = head;
    while( head ) {
        if(c%2 != 0) middle = middle->next;
        c++;
        head = head->next;
    }
    return middle->num;
}

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

int main()
{
    Node* head = NULL;

    insert(&head,1);
    insert(&head,3);
   insert(&head,5);
   insert(&head,7);
    cout << "Original list:\n";
    display_all_nodes(head); 
    cout << "\nMiddle element of the said list:";
    cout << "\n" << get_Middle(head) << "\n";
    cout << "\nOriginal list:\n";
    insert(&head,9);
    display_all_nodes(head); 
    cout << "\nMiddle element of the said list:";
    cout << "\n" << get_Middle(head);
    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:

Flowchart: Find middle element in a single linked list.
Flowchart: Find middle element in a single linked list.

CPP Code Editor:

Contribute your code and comments through Disqus.

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?



Follow us on Facebook and Twitter for latest update.

C++ Programming: Tips of the Day

How to use doxygen to create UML class diagrams from C++ source

Doxygen creates inheritance diagrams but I dont think it will create an entire class hierachy. It does allow you to use the GraphViz tool. If you use the Doxygen GUI frontend tool you will find the relevant options in Step2: -> Wizard tab -> Diagrams. The DOT relation options are under the Expert Tab.

Ref: https://bit.ly/3QUFLBY

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook