链表中一道较为中规中矩的题目。
题面如下:
素数链表
Problem Description
我们定义素数链表为元素全部是素数的链表。给定一个初始含有 n 个元素的链表,并给出 q 次删除操作,对于每次操作,你需要判断链表中指定位置上的元素,如果元素存在且不是素数则删除。Input
输入数据有多组。第 1 行输入 1 个整数 T (1 <= T <= 25) 表示数据组数。
对于每组数据:
•第 1 行输入 2 个整数 n (1 <= n <= 50000), q (1 <= q <= 1000) 表示链表初始元素数量和操作次数
•第 2 行输入 n 个用空格隔开的整数(范围 [0, 1000])表示初始链表
•接下来 q 行,每行输入 1 个整数 i (1 <= i <= 50000),表示试图删除链表中第 i 个元素
Output
对于每组数据:
•先输出 1 行 “#c”,其中 c 表示当前是第几组数据
•对于每次删除操作,根据情况输出 1 行:
◦如果要删除的位置不存在元素(位置超出链表长度),则输出 “Invalid Operation”
◦如果要删除的位置存在元素且此位置的元素是非素数,则删除元素并输出 “Deleted x”,其中 x 为成功删除的数(必须为非素数才能删除)
◦如果要删除的位置存在元素且此位置的元素是素数,则输出 “Failed to delete x”,其中 x 为此位置上的数
•删除操作全部进行完毕后,则还需判断该链表现在是否为一个素数链表。如果链表非空且是素数链表,则输出 “All Completed. It’s a Prime Linked List”,否则输出 “All Completed. It’s not a Prime Linked List”
所有输出均不包括引号。Example Input
2
1 2
0
5
1
6 3
1 2 3 3 4 5
1
1
4
Example Output
#1
Invalid Operation
Deleted 0
All Completed. It’s not a Prime Linked List
#2
Deleted 1
Failed to delete 2
Deleted 4
All Completed. It’s a Prime Linked List
经过读题发现本题用到链表的正序建立,链表的删除,查找,以及素数的判断,多加注意链表操作的细节。
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int f(int n)
{
int i, flag = 1;
if(n == 0 || n == 1) return 0;
for(i = 2; i <= sqrt(n); i++)
{
if(n % i == 0)
{
flag = 0;
break;
}
}
return flag;
}
struct node
{
int data;
struct node *next;
};
int count;
struct node *creat(int n);
struct node *del(struct node *head, int x);
void text(struct node *head);
int main()
{
int t, i, n, q, k, x;
while(~scanf("%d", &t))
{
for(k = 1; k <= t; k++)
{
struct node *head;
head = (struct node *) malloc (sizeof(struct node));
head->next = NULL;
printf("#%d\n", k);
count = 0;
scanf("%d %d", &n, &q);
head = creat(n);
count = n;
for(i = 1; i <= q; i++)
{
scanf("%d", &x);
if(x > count)
{
printf("Invalid Operation\n");
continue;
}
else head = del(head, x);
}
text(head);
}
}
return 0;
}
struct node *creat(int n)
{
int i;
struct node *head, *tail;
head = (struct node *) malloc (sizeof(struct node));
head->next = NULL;
tail = head;
for(i = 0; i <= n - 1; i++)
{
struct node *p;
p = (struct node *) malloc (sizeof(struct node));
p->next = NULL;
scanf("%d", &p->data);
p->next = tail->next;
tail->next = p;
tail = p;
}
return head;
};
struct node *del(struct node *head, int x)
{
int i;
struct node *q, *p;
q = head;
p = head->next;
for(i = 1; i < x; i++)
{
q = q->next;
p = p->next;
}
if(f(p->data) == 1) printf("Failed to delete %d\n", p->data);
else
{
printf("Deleted %d\n", p->data);
count--;
q->next = p->next;
}
return head;
};
void text(struct node *head)
{
if(count == 0)
{
printf("All Completed. It's not a Prime Linked List\n");
return;
}
int flag = 0;
struct node *p;
p = head->next;
while(p != NULL)
{
if(f(p->data) == 0)
{
printf("All Completed. It's not a Prime Linked List\n");
flag = 1;
break;
}
p = p->next;
}
if(flag == 0) printf("All Completed. It's a Prime Linked List\n");
};