6-23 逆序数据建立链表 (20 point(s))

By | 最新修改:2024-08-17

声明

这是 拼题A(PTA)《中M2019秋C入门和进阶练习集》的习题。原题在 https://pintia.cn/problem-sets/1163286449659043840/problems/1174288506294865942 (侵删)

本人的答案仅供交流学习,请勿用于当作答案来提交!

题目描述

6-23 逆序数据建立链表 (20 point(s))

本题要求实现一个函数,按输入数据的逆序建立一个链表。

函数接口定义:

struct ListNode *createlist();

函数createlist利用scanf从输入中获取一系列正整数,当读到−1时表示输入结束。按输入数据的逆序建立一个链表,并返回链表头指针。链表节点结构定义如下:

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

裁判测试程序样例:

#include 
#include 

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

struct ListNode *createlist();

int main()
{
    struct ListNode *p, *head = NULL;

    head = createlist();
    for ( p = head; p != NULL; p = p->next )
        printf("%d ", p->data);
    printf("\n");

    return 0;
}

// 你的代码将被嵌在这里

输入样例:
1 2 3 4 5 6 7 -1
输出样例:
7 6 5 4 3 2 1

我的答案

/*================================================================
*   Copyright (C) 2019 程序知路. All rights reserved.
*   
*   Filename    :6-23-逆序数据建立链表.c
*   Author      :程序知路
*   E-Mail      :admin@icxzl.com
*   Create Date :2019年10月25日
*   Description :
================================================================*/
#include 
#include 

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

struct ListNode *createlist();

int main()
{
    struct ListNode *p, *head = NULL;

    head = createlist();
    for ( p = head; p != NULL; p = p->next )
        printf("%d ", p->data);
    printf("\n");

    return 0;
}

// 以下是有效代码
struct ListNode *createlist() {
    static struct ListNode *head = NULL, *current = NULL, *prev = NULL;

    int input;
    scanf("%d", &input);

    if (input != -1) {
        createlist();
        if (!head) {
            head = (struct ListNode*) malloc(sizeof(struct ListNode));
            head->data = input;
            head->next = NULL;
            current = head;
        } else {
            current = (struct ListNode*) malloc(sizeof(struct ListNode));
            current->data = input;
            current->next = NULL;
            prev->next = current;
        }
        prev = current;
    } else {
        return NULL;
    }


    return head;
}


程序知路

鉴于本人的相关知识储备以及能力有限,本博客的观点和描述如有错漏或是有考虑不周到的地方还请多多包涵,欢迎互相探讨,一起学习,共同进步。

本文章可以转载,但是需要说明来源出处!

本文使用的部分图片来源于网上,若是侵权,请与本文作者联系删除: admin@icxzl.com