In: Computer Science
I want c++ /c program to build a double linked list and find with a function the middle element and its position and the linked list must be inserted by the user aand note You should handle the both cases of whether the size of the list even or odd
Program :
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *prev;
struct Node *next;
};
struct Node* head = NULL;
void insert(int n) {
struct Node* temp = (struct Node*) malloc(sizeof(struct
Node));
temp->data = n;
temp->prev = NULL;
temp->next = head;
if(head != NULL)
head->prev = temp;
head = temp;
}
void middle_element()
{
struct Node *ptr,*ptr1;
ptr=head;
ptr1=head;
int c=0;
while(ptr1!=NULL && ptr1->next!=NULL)
{
c=c+1;
ptr=ptr->next;
ptr1=ptr1->next->next;
}
cout<<"Middle of the element is:"<<ptr->data;
cout<<"\nPosition of middle element:"<<c;
}
int main() {
insert(23);
insert(89);
insert(90);
insert(10);
insert(56);
insert(78);
middle_element();
return 0;
}