Monday, October 8, 2012

Split list into two sublists

Write a function AlternatingSplit() which takes one list and divides up its nodes to make two smaller lists. The sublists should be made from alternating elements in the original list. So if the original list is {a, b, a, b, a}, then one sublist should be {a, a, a} and the other should be {b, b}.

/*
 * Give the source list, split its nodes into two shorter lists.
 * aRef should be set to point to the list of odd position elements,
 * and bRef should be set to point to the list of even position elements.
 * The elements in the new lists may be in any order.
 */
void Split(nodeptr source, nodeptr* aRef, nodeptr* bRef)
{
    nodeptr current , next, temp;
    if(source == NULL) {
        *aRef = NULL;
        *bRef = NULL;
    } else {
        current = source;
        next = current->next;
        *aRef = current;
        *bRef = next;
        while(next != NULL) {
            temp = next->next;
            current->next = temp;
            current = temp;
            if(current != NULL) {
                next->next = current->next;
                next = current->next;
            } else {
                next->next = NULL;
                next = NULL;
            }
        }
        if(current != NULL)
            current->next = NULL;
    }
}

No comments:

Post a Comment