【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

代码

c 复制代码
#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;  // 初始为空链表

    // 读取整数个数n
    scanf("%d", &n);

    // 顺次插入n个整数到表头
    for (int j = 0; j < n; j++) {
        scanf("%d", &data);
        Node* newNode = createNode(data);
        newNode->next = head;  // 新节点指向当前头节点
        head = newNode;        // 更新头节点为新节点
    }

    // 读取要查找的位序i
    scanf("%d", &i);

    // 输出第i个元素的值
    printf("%d\n", getElement(head, i));

    return 0;
}    
相关推荐
今晚打老虎4 小时前
c++之提高A(前缀和)(第三课)
数据结构·c++·算法
不会就选b5 小时前
算法日常・每日刷题--<贪心>26
数据结构·算法
铅笔小新z6 小时前
【C语言】操作符
c语言
by209997 小时前
从 malloc/free 到 new/delete:真正理解 C++ 中的内存管理与对象生命周期
c语言·c++·经验分享·动态内存管理
额额额对了7 小时前
SPI通信
linux·c语言·汇编·单片机·嵌入式硬件·arm
Logic1019 小时前
C语言/数据结构位运算题解:异或XOR找出书柜中编号只出现一次的那一层——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
青山木9 小时前
Hot 100 --- 下一个排列
java·数据结构·算法·leetcode
SelectDB技术团队11 小时前
Apache Doris 高性能 Open Lake Variant 读写技术解析(含对比数据)
数据结构·数据库·clickhouse·日志·apache doris·selectdb·湖仓架构升级
kiracrimson11 小时前
希尔排序:让插入排序不再怕逆序
数据结构·算法·排序算法
Logic10111 小时前
C语言/数据结构位运算题解:异或XOR找出星球探险中的“独特能量石“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质