单链表删除练习c语言

题目:

题目描述

试图编写一个链表,实现插入后,试着编写一下删除操作。(这种使用数组的方式可能会浪费内存,但是请暂时忽略这点)

作为练习的判断,请输出删除链表内所有元素x后的序列。数组保证删除后仍不为空。

输入格式

第一行包括一个数字n(n<100000),表示链表内元素的个数。

接下来一行,共n个整数,表示链表内的数据

接下来一个数字x,表示要删除的元素。

输出格式

一行,表示删除后的序列。

样例输入

8
2 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值