Program to split a linked list from a given position

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 split a linked list into two parts, given the position from which to start splitting*/
void split(struct list* head, struct list** dest, int position)
{
    int offset = 0;
    printf(“[%s][%d]\n”,__FUNCTION__,position);
    struct list* temp = NULL;
    struct list* newStart = NULL;
    while((offset < position -1) && (head->next != NULL))
    {
        head = head->next;
        offset++;
    }
    temp = head;   
    newStart = head->next;
    while(head->next != NULL)
    {
        *dest = head;
        head = head->next;
        (*dest) = (*dest)->next;
    }
    *dest = newStart;
    temp->next = NULL;
}

/* Function to use the linked list functions*/
int main()
{
    struct list* node = NULL;
    struct list* new = NULL;
    int i;
    for(i=0; i < 10; i++)
    {
        insert(&node,i);
    }
    split(node,&new,6);
    traverse(node);
    traverse(new);
    printf(“Old List length [%d]”,length(node));
    printf(“New List Length [%d]”,length(new));
}

Subscribe

Get articles in your inbox.

Enter your email address:

Join Us

Twitter Chatter


Recommendations

Archives

Categories