Categories
Programming

Algorithm to find the center of a list in O(n) time

Same technique can be used to find loops in a liked list. If you advance through the list one pointer at rate X, and another pointer through the list at rate (1/2)X then when the faster pointer is at the end of the list the slower pointer will be pointing to the center element of the list.

<pre class=code>

// findCenterElement – finds the element at the center of the list

node *findCenter(node *curList){

node *centerNode = curList;

node *curNode = curList;

if(curList == (node *)NULL)

return((node *)NULL);

if(curNode->next != (node *)NULL){

while(((curNode->next)->next) != (node *)NULL)

{

curNode = (curNode->next)->next;

centerNode = (centerNode->next);

}

}else{

return(curNode);

}

return(centerNode);

}

</pre>

Leave a Reply