向单链表里输入值的C语言程序怎么写
以下是一个简单的向单链表输入值的C语言程序:
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点结构体
struct Node {
int data;
struct Node *next;
};
int main() {
struct Node *head = NULL; // 定义链表头指针
struct Node *current = NULL; // 定义当前节点指针
int n, i, value;
printf("请输入链表节点个数:");
scanf("%d", &n);
// 输入链表节点的值
for (i = 1; i <= n; i++) {
printf("请输入第%d个节点的值:", i);
scanf("%d", &value);
// 创建新节点并赋值
struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = value;
new_node->next = NULL;
// 将新节点加入链表
if (head == NULL) { // 链表为空,新节点为第一个节点
head = new_node;
current = new_node;
} else { // 链表不为空,将新节点加入链表尾部
current->next = new_node;
current = new_node;
}
}
// 输出链表的值
printf("链表的值为:");
current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
return 0;
}
程序中首先定义了一个单链表节点结构体 Node,包含一个整型数据 data 和一个指向下一个节点的指针 next。然后定义了链表头指针 head 和当前节点指针 current,并输入了链表节点的个数 n 和每个节点的值。程序通过循环创建新节点并将其加入链表尾部,最后输出链表的值。
原文地址: https://www.cveoy.top/t/topic/btoZ 著作权归作者所有。请勿转载和采集!