洛谷—P3156 询问学号—链表题目(数据结构算法)
·

用链表写(超时):
#pragma warning(disable:4996)
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode {
int data;
struct LNode* next;
}LNode,*LinkList;
int InitList(LinkList& L)
{
if (L == NULL)
{
return 0;
}
L->next = NULL;
return 1;
}
void List_Create(LinkList& L, int n)
{
LNode* Temp,*list=L;
for (int i = 0; i < n; ++i)
{
Temp = (LNode*)malloc(sizeof(LNode));
if (Temp == NULL)
exit(1);
scanf("%d", &Temp->data);
Temp->next = NULL;
list->next = Temp;
list = Temp;
}
}
int Find_List(LinkList L, int m)
{
LNode* node = L->next;
int j = 1;
while (node != NULL && j < m)
{
node = node->next;
j++;
}
if (node != NULL)
{
printf("%d\n", node->data);
return 1;
}
return -1;
}
int main()
{
LNode* L;
L = (LNode*)malloc(sizeof(LNode));
InitList(L);
int n, m;
scanf("%d %d", &n, &m);
List_Create(L, n);
int query;
for (int i = 0; i < m; ++i)
{
scanf("%d", &query);
if (Find_List(L, query) == -1)
{
printf("ERROR");
}
}
free(L);
return 0;
}
数组写(AC):
#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, m;
scanf("%d %d", &n, &m);
int *students = (int*)malloc(n * sizeof(int));
if (students == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
for (int i = 0; i < n; i++) {
scanf("%d", &students[i]);
}
int query;
for (int i = 0; i < m; i++) {
scanf("%d", &query);
if (query > 0 && query <= n) {
printf("%d\n", students[query - 1]); // 数组索引从0开始,因此要减1
} else {
printf("ERROR\n"); // 查询超出范围
}
}
// 清理内存
free(students);
return 0;
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)