【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;
}    
相关推荐
深邃-16 小时前
【数据结构与算法】-二叉树(2):实现顺序结构二叉树(堆的实现),向上调整算法,向下调整算法,堆排序,TOP-K问题
数据结构·算法·二叉树·排序算法·堆排序··top-k
叼烟扛炮1 天前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
代码中介商1 天前
银行管理系统的业务血肉 —— 流程、状态机、输入校验与持久化(下篇)
c语言·算法
MegaDataFlowers1 天前
206.反转链表
数据结构·链表
爱编码的小八嘎1 天前
C语言完美演绎9-12
c语言
CN-Dust1 天前
【C++】while语句例题专题
数据结构·c++·算法
Navigator_Z1 天前
LeetCode //C - 1031. Maximum Sum of Two Non-Overlapping Subarrays
c语言·算法·leetcode
xieliyu.1 天前
Java手搓数据结构:从零模拟实现无头双向非循环链表
java·数据结构·链表
如何原谅奋力过但无声1 天前
【灵神高频面试题合集01-03】相向双指针、滑动窗口
数据结构·python·算法·leetcode
jieyucx1 天前
Go 数据结构入门:线性表、顺序表、链表
数据结构·链表·golang