【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;
}    
相关推荐
952363 小时前
并查集 / LRUCache
数据结构·算法
枫叶丹43 小时前
【Qt开发】Qt窗口(六) -> QMessageBox 消息对话框
c语言·开发语言·数据库·c++·qt·microsoft
缘三水3 小时前
【C语言】11.指针(1)
c语言·开发语言·指针
Miuney_MAX3 小时前
【电子电路】之Type-C正反插
c语言·开发语言
hefaxiang11 小时前
C语言常见概念(下)
c语言·开发语言
potato_may11 小时前
链式二叉树 —— 用指针构建的树形世界
c语言·数据结构·算法·链表·二叉树
Mz122111 小时前
day07 和为 K 的子数组
数据结构
Bona Sun13 小时前
单片机手搓掌上游戏机(二十)—pico运行doom之编译环境
c语言·c++·单片机·游戏机
Albert Edison13 小时前
【项目设计】C++ 高并发内存池
数据结构·c++·单例模式·哈希算法·高并发
我真不会起名字啊13 小时前
C、C++中的sprintf和stringstream的使用
java·c语言·c++