栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构-链表-删除所有值为x的结点

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构-链表-删除所有值为x的结点

题目:

将一个链表中元素值为x的结点删除。(链表数据域为整数,初始长为6个元素)
**输入提示信息:"输入数组%d个元素的值。n"
**输入格式:"%d"
**输出提示:"此链表各个结点的数据域为:"
**输出格式:"%d "
**输入提示信息:"输入要删除的数据x: "
**输入格式:"%d"
**输出提示: "删除后链表各个结点的数据域为:"
**输出格式:"%d "

#include
#include
#define N 6
struct note
{
    int i;
    struct note*next;
};
void freetem(struct note *head)
{
        struct note *pre=head;
        struct note *aft=head;
        while(aft!=NULL)
        {
            pre=aft;
            aft=pre->next;
            free(pre);
        }
}
struct note*  find(struct note*head,int x)
{
    struct note*p=head;
    struct note*pre=head;
    if(head->i==x)
    {
        p=p->next;
        head=p;
        pre->next=NULL;
        free(pre);

        return head;
    }

    while(p!=NULL&&p->next!=NULL)
    {
        pre=p;
        p=p->next;
        if(p->i==x)
        {
            pre->next=p->next;
            p->next=NULL;
            free(p);
            p=pre;
        }
    }

    return head;
}
main()
{
    int num[N],i=0;
    struct note*head=NULL;
    head=(struct note*)malloc(sizeof(struct note));
    if(head==NULL)
    {
        printf("error");
        exit(0);
    }
    printf("输入数组%d个元素的值。n",N);
    scanf("%d",&num[i]);
    head->i=num[i];
    struct note*p=head;
    for(i=1;i     {
        scanf("%d",&num[i]);
        struct note *pst=(struct note*)malloc(sizeof(struct note));
        if(head==NULL)
        {
            printf("error");
            exit(0);
        }
        pst->i=num[i];
        p->next=pst;
        pst->next=NULL;
        p=pst;
    }
    printf("此链表各个结点的数据域为:n");
    p=head;
    while(p!=NULL)
    {
        printf("%d ",p->i);
        p=p->next;
    }
     printf("输入要删除的数据x: ");
     int x;
     scanf("%d",&x);
     struct note*newhead=find(head,x);
     printf("删除后链表各个结点的数据域为:");
     p =newhead;
     while(p!=NULL)
    {
        printf("%d ",p->i);
        p=p->next;
    }
    freetem(head);
}
 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/935291.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号