素数链表问题

素数链表

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”
所有输出均不包括引号。

Samples
Sample #1
Input
2
1 2
0
5
1
6 3
1 2 3 3 4 5
1
1
4
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 <bits/stdc++.h>
using namespace std;
typedef struct node{
	int data;
	struct node *next;
}s;
int n,m,a,b,c,t,k=0;
struct node *creat(int n){
	s *head,*tail,*p;
	int a;
	head=(struct node *)malloc (sizeof(struct node));
	tail=head;
	tail->next=NULL;
	for(int i=1;i<=n;i++){
		cin>>a;
		p=(struct node *)malloc (sizeof(struct node));
		p->data=a;
		tail->next=p;
		tail=p;
		tail->next=NULL;
	}
	 
	return head;
};
int check(int a){
	if(a==1||a==0)
	   return 0;
	for(int i=2;i<=sqrt(a);i++){
		if(a%i==0)
		   return 0;
	}
	return 1;    
}
s *delet(s *head,int a){
	if(a>n)
		cout<<"Invalid Operation"<<endl;
	else{
		s *p,*r,*q;
	p=head->next;
	q=head;
	while(a-1){
		a--;
		p=p->next;
		q=q->next;
	}
	//检查是否为素数 
	if(check(p->data)==1)//是
		cout<<"Failed to delete "<<p->data<<endl;
	else{
	    q->next=p->next;
	    cout<<"Deleted "<<p->data<<endl;
	    p=q->next;
	    n--;
		}	 
		}
	return head;
};
void find(s *head,int n){
	s *p,*r,*q;
	p=head->next;
	if(p==NULL){
			cout<<"All Completed. It's not a Prime Linked List"<<endl;
	    	return;
	}
	else{
		while(p){
		int t=check(p->data);
		if(t==0){
			cout<<"All Completed. It's not a Prime Linked List"<<endl;
			return;
		}
		if(t==1){
			p=p->next;
		}
	}
	cout<<"All Completed. It's a Prime Linked List"<<endl;
	}	
}
int main(){
	int k=1;
	cin>>t;
	while(k<=t){
		cout<<"#"<<k<<endl;
		k++;
		cin>>n>>m;
        s *head,*p,*q,*r,*t;
        head=creat(n);
        for(int i=0;i<m;i++){
    	cin>>a;
    	head=delet(head,a);
	    }
		find(head,n);	
	}
    return 0;
}
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值