实验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;
} 
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1123 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19433 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww3 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚3 天前
[数据结构] 排序
数据结构
_不会dp不改名_3 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long3 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构