Tuesday, 17 May 2011

Find Middle of Linked List


#include
#include "linkedlist.h"

#define LL_LIMIT 6
int main()
{
int midData;
int index=LL_LIMIT;
NODE* headNode=NULL;
NODE* oneStepPtr=NULL;
NODE* twoStepPtr=NULL;

/* Create LL*/
while(index > 0)
{
headNode = addAtHead(headNode, index);
index--;
}

/* Display LL*/
displayAll(headNode);

oneStepPtr = headNode;
twoStepPtr = headNode;

/* Increment step pointers till the end */
while(twoStepPtr != NULL &&
twoStepPtr->next != NULL &&
twoStepPtr->next->next != NULL)
{
oneStepPtr = oneStepPtr->next;
twoStepPtr = twoStepPtr->next->next;
}
midData = oneStepPtr->data;

printf("Middle of LL contains %d\n", midData);
return 0;
}

No comments:

Post a Comment