寂寞梧桐221 2021-12-28 06:42 采纳率: 60%
浏览 51
已结题

双向链表中的结点删除问题

给出一个数x,从双向链表中删除所有元素x的结点

  • 写回答

4条回答 默认 最新

  • 关注

    大体思路是:
    (1)遍历链表
    (2)判断当前节点的data是否等于x
    (3)如果等于x,ppre记录上一个节点,nnext记录下一个节点,
    ppre->next = nnext; nnext->pre = ppre;
    删除当前节点的内存
    继续判断下一个节点。
    (4)如果不等于,继续遍历下一个节点

    img

    代码如下:

    #include <stdio.h>
    #include <stdlib.h>
    
    struct stnode 
    {
        int data;
        struct stnode* pre;
        struct stnode* next;
    };
    
    
    //创建双向链表
    struct stnode* create()
    {
        int i;
        struct stnode* head,*p,*t;
        head = (struct stnode*)malloc(sizeof(struct stnode));
        head->pre = NULL;
        head->next = NULL;
    
        t = head;
        //创建5个节点
        for (i=0;i<5;i++)
        {
            p = (struct stnode*)malloc(sizeof(struct stnode));
            p->pre = NULL;
            p->next = NULL;
            printf("请输入1个整数:");
            scanf("%d",&p->data);
            t->next = p;
            p->pre = t;
            t = p;
        }
        return head;
    }
    
    
    //删除值为x的节点
    struct stnode* del(struct stnode* head,int x)
    {
        struct stnode *p,*ppre,*nnext;
        p = head->next;
        while (p)
        {
            if(p->data == x)
            {
                ppre = p->pre;
                nnext = p->next;
                ppre->next = nnext;
                if(nnext)
                    nnext->pre = ppre;
                free(p);
                p = nnext;
            }else
                p = p->next;
        }
        return head;
    }
    
    //xians
    void show(struct stnode* head)
    {
        struct stnode* p = head->next;
        while(p)
        {
            printf("%d ",p->data);
            p = p->next;
        }
    }
    
    //free
    void Release(struct stnode* head)
    {
        struct stnode* p;
        while(head)
        {
            p = head->next;
            free(head);
            head = p;
        }
    }
    
    int main()
    {
        int x;
        struct stnode* head = create();
        show(head);
        printf("请输入需要删除的值:");
        scanf("%d",&x);
        head = del(head,x);
        //显示
        show(head);
        //释放空间
        Release(head);
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 1月11日
  • 已采纳回答 1月3日
  • 创建了问题 12月28日

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分