【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;
}    
相关推荐
Morwit6 分钟前
【力扣hot100】 1. 两数之和
数据结构·c++·算法·leetcode·职场和发展
hhh3u3u3u2 小时前
Visual C++ 6.0中文版安装包下载教程及win11安装教程
java·c语言·开发语言·c++·python·c#·vc-1
泛凡(Linyongui)2 小时前
PY32F002B实践之二--宠物腹背理疗仪项目介绍及头文件解析
c语言·keil·py32·32位单片机·腹背理疗仪项目实践
田梓燊3 小时前
2026/4/11 leetcode 3741
数据结构·算法·leetcode
葳_人生_蕤3 小时前
hot100——栈和队列
数据结构
网域小星球4 小时前
C 语言从 0 入门(十四)|文件操作:读写文本、保存数据持久化
c语言·开发语言·文件操作·fopen·fprintf
网域小星球4 小时前
C 语言从 0 入门(七)|字符数组与字符串完整精讲|VS2022 高质量实战
c语言·开发语言·字符串·vs2022·字符数组
Jia ming4 小时前
C语言实现日期天数计算
c语言·开发语言·算法
浅时光_c5 小时前
12 指针
c语言·开发语言
爱编码的小八嘎6 小时前
C语言完美演绎7-11
c语言