Algorithm To Find the Middle Element of Linked List
1. Take two pointers. Move first pointer by one and second pointer by two.
2. When second pointer reaches at end. First pointer reach at middle.
3. Print the value of first pointer which is the middle element.
Related Linked List Questions
Program to Reverse a Linked List
Program to Insert Node at the end of Linked List
Program to Find the Middle Element of Linked List
#include <stdio.h> struct node{ int data; struct node* next; }; struct node* head; void insert(int data){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->next = head; head = temp; } void middle(){
// Two pointers struct node* slow = head; struct node* fast = head; while(fast!=NULL && fast->next!=NULL){ slow = slow->next; // Move slow pointer by one fast = fast->next->next; // Move fast pointer by two } printf("\nmiddle element is %d",slow->data); } void print(){ struct node* temp = head; while(temp!=NULL){ printf("%d\n",temp->data); temp = temp->next; } } void main(){ head = NULL; insert(2); insert(4); insert(6); insert(7); insert(8); print(); middle(); }
No comments:
Post a Comment