Program to find the middle of a linked list

August 29th, 2009  |  Published in Amit Sahrawat, Data Structures, Linux Sample Programs








/* Structure for a linked list*/
struct list{
    int num;
    struct list* next; /* pointer to next node in list*/
};

/* Function to find the middle node for the linked list, given the starting node pointer*/
struct list* middle(struct list* head)
{
    struct list* far = NULL;
    printf(“[%s]\n”,__FUNCTION__);
    if(!head->next)
        return far=head;
    else{
        printf(“List not empty\n”);
        far = head->next;
        while((head->next) && (far->next))
        {
            head = head->next;           
            if(far->next->next)
                far = far->next->next;
            else
                break;
        }
    }
    return head;
}
/* Function to use the linked list functions*/
int main()
{
    struct list* node = NULL;
    for(i=0; i < 10; i++)
    {
        insert(&node,i);
    }
    struct list* mid = NULL;
    mid = middle(node);
    if(mid){
        printf(“[0x%x], num[%d]\n”,mid->num);
        traverse(mid);
    }
}

Subscribe

Get articles in your inbox.

Enter your email address:

Join Us

Twitter Chatter


Recommendations

Archives

Categories