【PTA数据结构 | C语言版】返回单链表 list 中第 i 个元素值
本专栏持续输出数据结构题目集,欢迎订阅。
文章目录
- 题目
- 代码
题目
请编写程序,将 n 个整数顺次插入一个初始为空的单链表的表头。对任一给定的位序 i(从 1 开始),输出链表中第 i 个元素的值。
输入格式:
输入首先在第一行给出非负整数 n(≤20);随后一行给出 n 个 int 范围内的正整数,数字间以空格分隔。最后一行给出位序 i,为 int 范围内的非负整数。
输出格式:
在一行中输出链表中第 i 个元素的值。如果这个元素不存在,则输出 -1。
输入样例 1:
5
1 2 3 4 5
4
输出样例 1:
2
输入样例 2:
5
1 2 3 4 5
0
输出样例 2:
-1
代码
#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;
}// 获取链表第i个元素的值
int getElement(Node* head, int i) {if (i < 1) return -1; // 位序i必须从1开始Node* current = head;int count = 1;while (current != NULL && count < i) {current = current->next;count++;}if (current == NULL) return -1; // 元素不存在return current->data;
}int main() {int n, data, i;Node* head = NULL; // 初始为空链表// 读取整数个数nscanf("%d", &n);// 顺次插入n个整数到表头for (int j = 0; j < n; j++) {scanf("%d", &data);Node* newNode = createNode(data);newNode->next = head; // 新节点指向当前头节点head = newNode; // 更新头节点为新节点}// 读取要查找的位序iscanf("%d", &i);// 输出第i个元素的值printf("%d\n", getElement(head, i));return 0;
}