Traversing a singly linked list with a dummy header

In this problem you will Implement a function to traverse a singly linked list with a dummy header and output the data field of each node.

Structure description:

The node structure is shown below:

复制代码
typedef struct ListNode {
    int data;
    struct ListNode *next;
} node;

typedef node* position;
typedef position List;

Function definition:

复制代码
void traversal(List L);

The parameter L is a pointer to the dummy header. The function outputs the data field of each node as it traverses the singly linked list.

Test program example:

cs 复制代码
#include <stdio.h>
#include <stdlib.h>

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

typedef node* position;
typedef position List;

void traversal(List L);

// The questioner has implemented the createList function.
// This function reads a series of positive integers separated by spaces
// and inserts them into a linked list using the head insertion method.
// Entering -1 indicates the end of input.
// creatgeList函数由题目提供,不需要在本题的答案中实现
List createList();

int main(void)
{
    List L = createList();
    traversal(L);
    return 0;
}

/* Please write the answer here */

Input Specification:

A series of positive integers separated by spaces. Entering -1 indicates the end of input.

Output Specification:

Output the data field of each node in the singly linked list. After each number, output a space.(每个整数后输出1个空格)

Sample Input :

复制代码
9 5 7 2 -1

Sample Output :

复制代码
2 7 5 9 

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

C程序如下:

cs 复制代码
void traversal(List L){ //遍历链表的函数,参数L是指向链表头节点的指针  
    if(L->next ==NULL){//检查该链表是否为空
        return;//如果为空则返回
    }
    L = L->next;//L指向该链表的第一个数据域
    while(L!=NULL){//遍历整个单链表
        printf("%d ", L->data);
        L= L->next;
    }
}
相关推荐
白熊18821 分钟前
【机器学习基础】机器学习入门核心算法:XGBoost 和 LightGBM
人工智能·算法·机器学习
bai_lan_ya1 小时前
数据结构-排序-排序的七种算法(2)
数据结构·算法·排序算法
泉飒1 小时前
lua注意事项
开发语言·笔记·lua
hao_wujing2 小时前
使用逆强化学习对网络攻击者的行为偏好进行建模
开发语言·网络·php
还是鼠鼠2 小时前
单元测试-概述&入门
java·开发语言·后端·单元测试·log4j·maven
全域智图2 小时前
元胞自动机(Cellular Automata, CA)
人工智能·算法·机器学习
珂朵莉MM2 小时前
2022 RoboCom 世界机器人开发者大赛-本科组(省赛)解题报告 | 珂学家
人工智能·算法·职场和发展·深度优先·图论
独家回忆3642 小时前
每日算法-250601
数据结构·算法
YONYON-R&D3 小时前
DEEPSEEK帮写的STM32消息流函数,直接可用.已经测试
算法·消息流
明月看潮生3 小时前
青少年编程与数学 02-020 C#程序设计基础 14课题、程序调试
开发语言·青少年编程·c#·编程与数学