实验11-2-3 逆序数据建立链表 (20 分)

实验11-2-3 逆序数据建立链表 (20 分)

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

函数接口定义:
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

复制代码
struct ListNode *createlist()
{
  int num;
  struct ListNode *ptr=NULL,*head=NULL,*tail=NULL;
  scanf("%d",&num);
  while(num!=-1)
  {
    ptr=(struct ListNode *)malloc(sizeof(struct ListNode));
    ptr->data=num;
    ptr->next=head;
    head=ptr;
    scanf("%d",&num);
  }
  return head;
} 
相关推荐
All for pursuit.4 分钟前
【动态规划-6】96.不同的二叉搜索树
数据结构·c++·算法·leetcode·动态规划
信奥卷王34 分钟前
[GESP202609 六级] 数组划分
数据结构·算法
All for pursuit.2 小时前
【并查集-2】399.除法求值
数据结构·c++·算法·leetcode
殷色玫瑰5 小时前
AVL树:从平衡因子到四种旋转的完整实现
c语言·数据结构·c++·算法·visualstudio
y1su6 小时前
Leetcode 二分模板
java·数据结构·算法·leetcode·排序算法
bksczm6 小时前
数据结构的大纲概括
数据结构
千千寰宇6 小时前
[数据库系统] 数据库系统的设计原理研究
数据结构·数据库·database-opengemini/influxdb·database-dament/达梦
殷色玫瑰7 小时前
C++ STL:map 与 set 详解——从底层红黑树到实际应用
c语言·数据结构·c++·算法·visualstudio·rpc
字节跳动的猫8 小时前
LikeShop 商品评价体系二开:追评、晒图审核与评价标签筛选功能开发
运维·数据结构·数据库
All for pursuit.9 小时前
【动态规划-8】152.乘积最大子数组
数据结构·c++·算法·leetcode·动态规划