逆序数据建立链表

struct ListNode *createlist()
{
    int k=0;
    scanf("%d",&k);
    struct ListNode*head=(struct ListNode*)malloc(sizeof(struct ListNode));
    head->data=0;
    head->next=NULL;
    while(k>=0)
    {
        struct ListNode*new=(struct ListNode*)malloc(sizeof(struct ListNode));
        new->next=head->next;
        head->next=new;
        new->data=k;
        scanf("%d",&k);
    }
    return head->next;
}

1.不需要添加头节点

2.头插链表

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

函数接口定义:

 

struct ListNode *createlist();

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

 

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

裁判测试程序样例:

 

#include <stdio.h> #include <stdlib.h> 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 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值