实验11-2-6 奇数值结点链表 (20 分)

#include <stdio.h>
#include <stdlib.h>

struct ListNode {
    int data;
    struct ListNode *next;
};

struct ListNode *readlist();
struct ListNode *getodd(struct ListNode **L);
void printlist(struct ListNode *L)
{
    struct ListNode *p = L;
    while (p) {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

int main()
{
    struct ListNode *L, *Odd;
    L = readlist();
    Odd = getodd(&L);
    printlist(Odd);
    printlist(L);

    system("pause");
    return 0;
}

/* 你的代码将被嵌在这里 */
struct ListNode *readlist() {
    struct ListNode *head = NULL, *tail = NULL, *p;
    int x;
    head = (struct ListNode *)malloc(sizeof(struct ListNode));
    head->data = scanf("%d", &x);
    p = head;
    while (scanf("%d", &x) && x != -1) {
        tail = (struct ListNode *)malloc(sizeof(struct ListNode));
        tail->data = x;
        p->next = tail;
        p = tail;
    }
    tail->next = NULL;
    return head;
}

struct ListNode *getodd(struct ListNode **L) {
    struct ListNode *head1 = NULL, *tail1 = NULL, *head2 = NULL, *tail2 = NULL, *p = *L;
    while (p != NULL) {
        if (p->data % 2 != 0) {
            if (head1 == NULL) 
                head1 = tail1 = p;
            else {
                tail1->next = p;
                tail1 = p;
            }
            p = p->next;
            tail1->next = NULL;
        }
        else {
            if (head2 == NULL) 
                head2 = tail2 = p;
            else {
                tail2->next = p;
                tail2 = p;
            }
            p = p->next;
            tail2->next = NULL;
        }
    }
    *L = head2;
    return head1;
}

 

posted @ 2022-03-09 10:28  JamesGordan  阅读(76)  评论(0)    收藏  举报