题目链接:点击打开链接
链表-删除指定元素
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
对于一个给定的线性表,要求删除线性表内的大于等于 min 且小于等于 max 的数,并输出删除后的线性表
要求:必须使用链表做,否则不计成绩!
输入
输入的第一行为一个正整数 T,表示有 T 组测试数据。
每组测试数据的第一行为三个整数n、min、max,表示有 n 个数据,删除的范围为[min, max].第二行为 n 个整数代表初始的 n 个数据。
输出
输出删除数据后的线性表,如果线性表为空则输出-1
示例输入
2
3 1 2
1 2 3
5 2 1
1 1 1 1 1
示例输出
3
1 1 1 1 1
代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct node
{
int data;
node *next;
};
node *create(int n)
{
node *head,*tail,*p;
head=new node;
head->next=NULL;
tail=head;
for(int i=0; i<n; i++)
{
p=new node;
scanf("%d",&p->data);
tail->next=p;
p->next=NULL;
tail=p;
}
return head;
}
node *Del(node *head,int n,int m)
{
node *p,*q;
p=head;
if(n>m)
return head;
else
{
while(p->next)
{
q=p->next;
if(q->data>=n&&q->data<=m)
{
p->next=q->next;
free(q);
q=p->next;
}
else
{
p=q;
q=q->next;
}
}
}
return head;
}
void print(node *head)
{
node *p;
p=head->next;
while(p)
{
if(p->next)
printf("%d ",p->data);
else
printf("%d\n",p->data);
p=p->next;
}
}
int main()
{
node *head;
int n,m,t,k;
scanf("%d",&k);
while(k--)
{
scanf("%d%d%d",&t,&n,&m);
head=create(t);
head=Del(head,n,m);
if(head->next==NULL)
printf("-1\n");///如果线性表为空则输出-1
else
print(head);
}
return 0;
}