题目:
题目描述
试图编写一个链表,实现插入后,试着编写一下删除操作。(这种使用数组的方式可能会浪费内存,但是请暂时忽略这点)
作为练习的判断,请输出删除链表内所有元素x后的序列。数组保证删除后仍不为空。
输入格式
第一行包括一个数字n(n<100000),表示链表内元素的个数。
接下来一行,共n个整数,表示链表内的数据
接下来一个数字x,表示要删除的元素。
输出格式
一行,表示删除后的序列。
样例输入
82 3 4 4 4 5 3 8
4
样例输出
2 3 5 3 8
#include<stdio.h>
#include<malloc.h>
struct lian{
int shu;
struct lian* next;
};
struct lian*chu(int n)//创建链表
{int c=0;
struct lian*head=(struct lian*)malloc(sizeof(struct lian));
struct lian*p=head;
head->shu=0;
head->next=NULL;
struct lian*ne=(struct lian*)malloc(sizeof(struct lian));
int x;
while(c!=n){
scanf("%d ",&x);
ne=(struct lian*)malloc(sizeof(struct lian));
ne->shu=x;
ne->next=NULL;
p->next=ne;
p=ne;
c++;
}
return head;
}
void print(struct lian*head)//打印链表
{
if(head==NULL)return ;
struct lian*p=head->next;
while(p!=NULL){
printf("%d ",p->shu);
p=p->next;
}
}
void del(struct lian*head,int s)//删除1次要删除的数
{
if(head==NULL)return ;
struct lian*p=head;
struct lian*p2=p->next;
while(p2!=NULL){
if(p2->shu==s)break;
p=p2;
p2=p2->next;
}
if(p2==NULL)return ;
p->next=p2->next;
free(p2);
p2=NULL;
}
int main()
{
int n,s,i;
scanf("%d",&n);
struct lian*head=chu(n);
scanf("%d",&s);
for(i=0;i<n;i++) del(head,s); //查找n次,若有要删除的就删除,没有不做操作
print(head);
return 0;
}