头插法创建单链表、遍历链表、删除链表 | 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;
}
相关推荐
北域码匠39 分钟前
Karatsuba乘法超详细解析(原理+流程+性能分析+纯原生C#无第三方库完整实现)
算法·c#·大数乘法·高精度计算·数据结构与算法·分治算法·karatsuba 乘法
exm-zem44 分钟前
从C语言到C++:C++入门1
c语言·c++
fpcc1 小时前
数据结构和算法—数学的应用
数据结构·c++·算法
皓月斯语1 小时前
B4451 [GESP202512 四级] 建造 题解
数据结构·c++·算法·题解
小喻同学i1 小时前
std::thread函数参数传递
开发语言·c++
z小猫不吃鱼2 小时前
模型剪枝经典论文精读:DepGraph: Towards Any Structural Pruning
算法·机器学习·剪枝
Ulyanov3 小时前
Python实现6-DOF刚体仿真器(下)——环境扰动与控制闭环
开发语言·python·算法·系统仿真·雷达电子对抗·导引头
牧以南歌〆3 小时前
数据结构<八>链式队列
c语言·数据结构·算法
Reart3 小时前
Leetcode 188.买卖股票的最佳时机4(718)
后端·算法
2601_950760793 小时前
BCMA:急性髓系白血病免疫治疗的新型可行靶点
人工智能·算法·蛋白