Middle Element of Linked List

[wpdm_package id=’1377′]
Algorithm

    1. Keep two pointer c and m.
    2. Always move c pointer at twice the speed of m pointer.
    3. If the linked list length is even that middle element will be n/2 element. If linked list length is odd then the middle element will be (n/2 + 1) element.

LinkedList_Middle_Element

[sourcecode lang=”cpp”]
int Middle_Element(intnode *n){
intnode *c,*m;
int x=0;
c=m=n;
while(c->next!=NULL){
if(x==0){
c=c->next;
x=1;
}
else{
c=c->next;
m=m->next;
x=0;
}
}
return m->data;
}
[/sourcecode]

Leave a Reply

Your email address will not be published. Required fields are marked *