从在C双向链表中删除节点 [英] Removing a Node from a Doubly Linked List in C

查看:849
本文介绍了从在C双向链表中删除节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个整体我的计划是为插入和删除在排序的双向链表节点。插入工程和删除链表的第一个节点工作正常,但删除最后一个节点。另外,在中部和端删除节点不工作。如果我尝试删除最后一个节点,导致我回到主();如果我尝试删除中间节点,程序崩溃。你的帮助是AP preciated!

 无效删除(INT N){
    结构节点*帮助=头;
    如果(流浆>数据== N){
        如果(流浆>下面)
            帮助 - >下一步 - > preV = NULL;
        头=帮助 - >接下来,
    }其他{
        而(帮助){
            如果(帮助 - >数据== N){
                如果(帮助 - >下面)
                    帮助 - >下一步 - > preV =帮助 - > preV;
                帮助 - > preV->接下来=帮助 - >接下来,
            }其他帮助=帮助 - >接下来,
        }
    }
}


解决方案

无论你打破while循环或更新帮助指向下一个项目时,如果(Help(帮助)方式>数据==ñ是真的

的东西

  //你的code
    ...
    而(帮助){
        如果(帮助 - >数据== N){
            如果(帮助 - >下面)
                帮助 - >下一步 - > preV =帮助 - > preV;
            帮助 - > preV->接下来=帮助 - >接下来,
            //如果你不想删除具有数据'N'的所有节点
            打破;
        }
        //如果你想删除的数据有N的所有节点删除其他。
        //但要帮助=帮助 - >接下来
        其他
           帮助=帮助 - >接下来,    ...
     //你的code

As a whole my program is for inserting and deleting nodes in a sorted doubly linked list. Insertion works and deleting the first node from the linked list works fine, except deleting the last node. Also, deleting nodes in the middle and end don't work. If I try to delete the last node, I am led back to main(); If I try deleting a node in the middle, the program crashes. Your help is appreciated!

void remove(int n){
    struct node* help = head;
    if(head->data == n){
        if (head->next)
            help->next->prev = NULL;
        head = help->next;
    } else{
        while(help){
            if(help->data == n){
                if(help->next)
                    help->next->prev = help->prev;
                help->prev->next = help->next;
            } else help = help->next;
        }
    }
}

解决方案

Either you break your while loop or update the help pointer to next item when if(help->data ==n is true.

Something like

    //your code
    ...
    while(help){
        if(help->data == n){
            if(help->next)
                help->next->prev = help->prev;
            help->prev->next = help->next;
            //if you don't want to remove all nodes that have data 'n'
            break;
        } 
        //if you want to remove all nodes that have data 'n' remove else. 
        //but keep help = help->next
        else 
           help = help->next;

    ...
     //your code

这篇关于从在C双向链表中删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆