【PTA数据结构 | C语言版】在单链表 list 中查找元素 x 所在结点

本专栏持续输出数据结构题目集,欢迎订阅。

文章目录

题目

请编写程序,将 n 个整数顺次插入一个初始为空的单链表的表头。对任一给定的整数 x,查找其是否在链表中。

输入格式:

输入首先在第一行给出非负整数 n(≤20);随后一行给出 n 个 int 范围内的整数,数字间以空格分隔。最后一行给出待查找的 x,为 int 范围内的整数。

输出格式:

如果找到了 x 所在的位置,则输出该位置上链表结点的数据;否则在一行中输出 x 未找到。,其中 x 是输入的 x 的值。

输入样例 1:

5

1 2 3 4 5

4

输出样例 1:

4

输入样例 2:

5

1 2 3 4 5

0

输出样例 2:

0 未找到。

代码

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;
}

// 查找元素x是否在链表中
int findElement(Node* head, int x) {
    Node* current = head;
    while (current != NULL) {
        if (current->data == x) {
            return 1;  // 找到元素
        }
        current = current->next;
    }
    return 0;  // 未找到元素
}


int main() {
    int n, data, x;
    Node* head = NULL;  // 初始为空链表

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

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

    scanf("%d", &x);

    // 查找元素x
    if (findElement(head, x)) {
        printf("%d\n", x);
    } else {
        printf("%d 未找到。\n", x);
    }

    return 0;
}