Loading

习题11-7 奇数值结点链表 (20分)

本题要求实现两个函数,分别将读入的数据存储为单链表、将链表中奇数值的结点重新组成一个新的链表。

  • 核心
  1. 单链表的建立
struct ListNode *readlist()
{
    struct ListNode *head, *tail, *p;
    int n;
    head = NULL;
    tail = head;
    
    while(n != -1)
    {
        scanf("%d", &n);
        if (n != -1)
        {
            p = (struct ListNode*)malloc(sizeof(struct ListNode));  // 申请新节点
            p -> data = n;
            p -> next = NULL;

            if (head == NULL) head = p;  // 若为头节点时
            else tail -> next = p;  

            tail = p;
        }
    }
    return head;
}
  1. 奇数偶数分离
struct ListNode *getodd( struct ListNode **L )
{
    struct ListNode *p, *p1, *p2, *h1 = NULL, *h2 = NULL;
    int a;

    while(*L)
    {
        a = (*L) -> data;

        p = (struct ListNode*)malloc(sizeof(struct ListNode));
        p -> data = a;
        p -> next = NULL;

        if (a % 2 == 1)
        {
            if (h1 == NULL) h1 = p;
            else p1 -> next = p;

            p1 = p;
        }
        else
        {
            if (h2 == NULL) h2 = p;
            else p2 -> next = p;

            p2 = p;
        }
        
        (*L) = (*L) -> next;

    }

    *L = h2;
    return h1;
}

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

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

// 单链表的建立
struct ListNode *readlist()
{
    struct ListNode *head, *tail, *p;
    int n;
    head = NULL;
    tail = head;
    
    while(n != -1)
    {
        scanf("%d", &n);
        if (n != -1)
        {
            p = (struct ListNode*)malloc(sizeof(struct ListNode));  // 申请新节点
            p -> data = n;
            p -> next = NULL;

            if (head == NULL) head = p;  // 若为头节点时
            else tail -> next = p;  

            tail = p;
        }
    }
    return head;
}

struct ListNode *getodd( struct ListNode **L )
{
    struct ListNode *p, *p1, *p2, *h1 = NULL, *h2 = NULL;
    int a;

    while(*L)
    {
        a = (*L) -> data;

        p = (struct ListNode*)malloc(sizeof(struct ListNode));
        p -> data = a;
        p -> next = NULL;

        if (a % 2 == 1)
        {
            if (h1 == NULL) h1 = p;
            else p1 -> next = p;

            p1 = p;
        }
        else
        {
            if (h2 == NULL) h2 = p;
            else p2 -> next = p;

            p2 = p;
        }
        
        (*L) = (*L) -> next;

    }

    *L = h2;
    return h1;
}


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);

    return 0;
}

/* 你的代码将被嵌在这里 */
posted @ 2020-07-05 21:00  啊哈小张同学  阅读(782)  评论(0)    收藏  举报