145. 奇前偶後

 avatar
user_6817964
c_cpp
3 years ago
1.5 kB
4
Indexable
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
    int val;
    struct ListNode* next;
};

struct ListNode* oddEvenList(struct ListNode* head);

struct ListNode* oddEvenList(struct ListNode* head)
{
    int count = 0, odd = 0, even = 1, get[1000];
    struct ListNode* ptr = head;

    while (ptr != NULL) {
        get[count] = ptr->val;
        count++;
        ptr = ptr->next;
    }

    ptr = head;

    while (odd < count) {
        ptr->val = get[odd];
        odd += 2;
        ptr = ptr->next;
    }

    while (even < count) {
        ptr->val = get[even];
        even += 2;
        ptr = ptr->next;
    }

    return head;
}

void Construct(struct ListNode* node, int length, int num)
{
    int a;
    scanf("%d", &a);
    node->val = a;

    if (num >= length)
    {
        node->next = NULL;
        return;
    }
    node->next = (struct ListNode*)malloc(sizeof(struct ListNode));
    num++;
    Construct(node->next, length, num);
}

int main()
{
    struct ListNode* head;
    int n, a, length;
    head = (struct ListNode*)malloc(sizeof(struct ListNode));
    scanf("%d", &n);
    while (n--)
    {
        scanf("%d", &length);
        Construct(head, length, 1);
        struct ListNode* ans = oddEvenList(head);
        struct ListNode* ptr;

        ptr = ans;

        while (ptr != NULL)
        {
            printf("%d ", ptr->val);
            ptr = ptr->next;
        }
        printf("\n");
    }
}
Editor is loading...