实验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;
} 
相关推荐
代码游侠1 分钟前
学习笔记——栈
开发语言·数据结构·笔记·学习·算法
Ayanami_Reii11 分钟前
进阶数据结构应用-维护序列
数据结构·算法·线段树
CoderYanger22 分钟前
C.滑动窗口-越长越合法/求最短/最小——2904. 最短且字典序最小的美丽子字符串
java·开发语言·数据结构·算法·leetcode·1024程序员节
别动哪条鱼1 小时前
FFmpeg API 数据结构及其详细说明:
数据结构·ffmpeg·音视频·aac
Ayanami_Reii1 小时前
进阶数据结构-线段树
数据结构·算法·线段树
liu****1 小时前
11.字符函数和字符串函数(一)
linux·运维·c语言·开发语言·数据结构·算法
!chen1 小时前
SQL Server 2025 新功能概览
数据结构
埃伊蟹黄面1 小时前
双指针算法
数据结构·c++·算法
java修仙传1 小时前
力扣hot100:反转链表
算法·leetcode·链表
Elias不吃糖2 小时前
Leetcode-10.正则表达式匹配(暴力 或 记忆暴力)
数据结构·c++·算法·leetcode·深度优先