328 odd even linked list

把奇数位的数依次放入一个链表,偶数位的数放入另外一个链表,
然后奇数位链表的末尾指向偶数位的链表,同时把偶数位的链表末尾设置为NULL(容易忘记,切记!!!)

struct ListNode* oddEvenList(struct ListNode* head) {
    struct ListNode *odd = calloc(1, sizeof(struct ListNode));
    struct ListNode *even = calloc(1, sizeof(struct ListNode));

    struct ListNode *lastodd, *lasteven;
    lastodd = odd;
    lasteven = even;
    int oddtag = 1;
    struct ListNode * p = head;
    while(p){
        if(oddtag){
            lastodd->next = p;
            lastodd = lastodd->next;
            oddtag = 0;
        }else{
            lasteven->next = p;
            lasteven = lasteven->next;
            oddtag = 1;
        }

        p = p->next;

    }

    lastodd->next = even->next;
    lasteven->next = NULL;

    free(odd);
    free(even);
    return head;

}

你可能感兴趣的:(328 odd even linked list)