头插法创建单链表、遍历链表、删除链表 | C语言代码

题目:

输入一系列自然数(0和正整数),输入-1时表示输入结束。按照输入的顺序,用头插法建立单链表,并遍历所建立的单链表,输出这些数据。注意 -1 不加入链表。

输入格式:

第一行是一个正整数k,表示以下会有k组测试数据。

每组测试数据是一系列以空格隔开的自然数(0和正整数)。数列末尾的 -1 表示本组测试数据结束。按照输入的顺序,用头插法建立单链表,并遍历所建立的单链表,输出这些数据。注意 -1 不加入链表。

输出格式:

对于每组测试数据,输出链表中各节点的数据域。每个数据后有一个空格。每组测试数据的输出占1行。

输入样例:

3

1 2 3 4 5 -1

30 20 10 -1

4 2 2 1 1 2 0 2 -1

输出样例:

5 4 3 2 1

10 20 30

2 0 2 1 1 2 2 4

代码:

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

// 定义单链表节点结构
struct Node {
    int data; // 数据域
    struct Node* next; // 指针域
};

// 创建链表的函数
struct Node* createLinkedList() {
    struct Node* head = NULL;
    int value;
 	
 	// 输入链表元素
    while (1) {
        scanf("%d", &value);
        
		// 判断是否插入节点
        if (value == -1) {
            break;
        }

		// 头插法
        struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
        newNode->data = value;
        newNode->next = head;
        head = newNode;
    }

    return head;
}

// 遍历链表
void traverseAndPrint(struct Node* head) {
    struct Node* current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

// 删除链表释放内存
void deleteLinkedList(struct Node* head) {
    struct Node* current = head;
    while (current != NULL) {
        struct Node* temp = current;
        current = current->next;
        free(temp);
    }
}

int main() {
	// 输入链表节点个数
    int k;
    scanf("%d", &k);

	// 输入元素
    for (int i = 0; i < k; i++) {
        struct Node* head = createLinkedList();
        traverseAndPrint(head);
        deleteLinkedList(head);
    }

    return 0;
}
相关推荐
阿猿收手吧!5 分钟前
【C++】JSON核心数据结构解析及JSONCPP使用
数据结构·c++·json
leo__5206 分钟前
基于C语言的FOC算法核心模块实现
c语言·算法·机器学习
kisshuan123967 分钟前
仪表盘数字识别-基于YOLOv8改进的EUCB-SC算法实现
算法·yolo
tobias.b8 分钟前
408真题解析-2009-9-数据结构-小根堆-排序
数据结构·408考研·408真题·真题解析
报错小能手18 分钟前
线程池学习(二)线程池详解
c++·线程池
w-w0w-w18 分钟前
C++泛型编程
开发语言·c++·算法
-西门吹雪24 分钟前
C++线程之内存模型
c++
alphaTao34 分钟前
LeetCode 每日一题 2025/12/29-2026/1/4
算法·leetcode
ShaderJoy34 分钟前
ShaderJoy —— 《对称镜面下的绞肉机》【算法悬疑短文】【Python】
算法·leetcode·面试
智驱力人工智能37 分钟前
在安全与尊严之间 特殊人员离岗检测系统的技术实现与伦理实践 高风险人员脱岗预警 人员离岗实时合规检测 监狱囚犯脱岗行为AI分析方案
人工智能·深度学习·opencv·算法·目标检测·cnn·边缘计算