C语言链表创建与显示示例 - 代码详解
#include <stdio.h> #include <stdlib.h>
//定义链表节点的结构体 typedef struct ListNode { int val; //存储节点的值 struct ListNode *next; //指向下一个节点的指针 } ListNode;
//创建链表的函数
ListNode* createList(int n) {
ListNode* head = NULL; //链表的头指针
ListNode* tail = NULL; //链表的尾指针
int i, val;
for (i = 0; i < n; i++) {
printf("请输入第%d个节点的值:", i+1);
scanf("%d", &val); //输入节点的值
ListNode* node = (ListNode*)malloc(sizeof(ListNode)); //创建新节点
node->val = val;
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head; //返回链表的头指针
}
//显示链表的函数 void displayList(ListNode* head) { ListNode* p = head; int count = 0; printf("链表中元素个数为:"); while (p != NULL) { //遍历链表 count++; printf("%d ", p->val); //输出节点的值 p = p->next; } printf("\n"); printf("链表中元素为:"); p = head; while (p != NULL) { //再次遍历链表 printf("%d ", p->val); //输出节点的值 p = p->next; } printf("\n"); }
int main() { int n; printf("请输入链表中元素的个数:"); scanf("%d", &n); //输入链表的大小 ListNode* head = createList(n); //创建链表 displayList(head); //显示链表 return 0;
原文地址: https://www.cveoy.top/t/topic/nraU 著作权归作者所有。请勿转载和采集!