#include <iostream>
#include<math.h>
using namespace std;
struct list
{
int data;
struct list *next;
};
typedef struct list node;
node *head;
void insert_node()
{
node *temp=new node();
node *last;
cout<<"Data: ";
cin>>temp->data;
temp->next=NULL;
if(head==NULL)
{
head = temp;
}
else
{
last = head;
while(last->next != NULL)
{
last = last->next;
}
last->next = temp;
}
}
void print_node()
{
node *temp=head;
if(head==NULL)
{
}
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
}
void find_middle()
{
node *temp=head;
int count=0,i=0;
while(temp->next!=NULL) ///count total value
{
count++;
temp=temp->next;
}
count = count /2;
count= ceil(count); ///find the ceiling value
temp=head;
while(i!=count) ///find middle element
{
i++;
temp=temp->next;
}
cout<<"The Middle Element: "<<temp->data<<endl;
}
int main()
{
int flag;
do
{
cout<<"Press 1 to Enter New Node: ";
cin>>flag;
if(flag!=1) break;
insert_node();
}while(flag==1);
cout<<"Your Linked List: ";
print_node();
find_middle();
return 0;
}
Output
Press 1 to Enter New Node: 1
Data: 1
Press 1 to Enter New Node: 1
Data: 2
Press 1 to Enter New Node: 1
Data: 3
Press 1 to Enter New Node: 1
Data: 4
Press 1 to Enter New Node: 1
Data: 5
Press 1 to Enter New Node: 0
Your Linked List: 1 2 3 4 5
The Middle Element: 3
Add your comment