实验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;
} 
相关推荐
多米Domi0116 分钟前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
曹仙逸1 小时前
数据结构day04
数据结构
Lips6111 小时前
2026.1.16力扣刷题
数据结构·算法·leetcode
曹仙逸1 小时前
数据结构day05
数据结构
睡一觉就好了。2 小时前
树的基本结构
数据结构
kaikaile19952 小时前
A星算法避开障碍物寻找最优路径(MATLAB实现)
数据结构·算法·matlab
今天_也很困3 小时前
LeetCode 热题100-15.三数之和
数据结构·算法·leetcode
思成Codes4 小时前
ACM训练:接雨水3.0——动态接雨水
数据结构·算法
sin_hielo4 小时前
leetcode 2943
数据结构·算法·leetcode
Snow_day.5 小时前
有关平衡树
数据结构·算法·贪心算法·动态规划·图论