【PTA数据结构 | C语言版】求单链表list中的元素个数,即表长
本专栏持续输出数据结构题目集,欢迎订阅。
文章目录
- 题目
- 代码
题目
请编写程序,将 n 个整数顺次插入一个初始为空的单链表的表头。最后输出单链表的表长。
本题旨在训练学习者熟悉单链表的基本操作,不建议直接输出 n。
输入格式:
输入首先在第一行给出非负整数 n(≤15);随后一行给出 n 个 int 范围内的整数,数字间以空格分隔。
输出格式:
在一行中输出单链表的表长。
输入样例:
5
1 2 3 4 5
输出样例:
5
代码
#include <stdio.h>
#include <stdlib.h>// 定义链表节点结构
typedef struct Node {int data;struct Node* next;
} Node;// 创建新节点
Node* createNode(int data) {Node* newNode = (Node*)malloc(sizeof(Node));newNode->data = data;newNode->next = NULL;return newNode;
}// 计算链表长度
int getLength(Node* head) {int count = 0;Node* current = head;while (current != NULL) {count++;current = current->next;}return count;
}// 释放链表内存
void freeList(Node* head) {Node* temp;while (head != NULL) {temp = head;head = head->next;free(temp);}
}int main() {int n, data;Node* head = NULL; // 初始为空链表// 读取整数个数nscanf("%d", &n);// 顺次插入n个整数到表头for (int i = 0; i < n; i++) {scanf("%d", &data);Node* newNode = createNode(data);newNode->next = head; // 新节点指向当前头节点head = newNode; // 更新头节点为新节点}// 计算并输出链表长度printf("%d\n", getLength(head));// 释放链表内存freeList(head);return 0;
}