循环链表

时间:2017-03-03 10:01:33

标签: c++ linked-list nodes doubly-linked-list circular-list

上下文:从文件(input.txt)创建一个循环的双向链表,其中包含一个名称列表。名称数量未知。

提示用户输入要删除的节点数,然后从列表中删除。

假设:用户输入的数字不会超过列表中的实际节点数。

问题:我的删除节点功能不起作用,因为当我去显示被认为已删除的节点中的内容时,数据仍然存在。任何帮助?

我的代码:http://www.cplusplus.com/forum/general/210015/

(我正在链接到其他网站,因为它更容易格式化。)

3 个答案:

答案 0 :(得分:2)

  

我的删除节点功能不起作用,因为当我去显示被认为已删除的节点中的内容时,数据仍然存在。

访问已销毁(已删除)的对象具有未定义的行为。

当行为未定义时,您无法期望程序的行为方式。因此期望 "数据不应该在那里" 是没有根据的。正确的期望是数据可能会或可能不存在,并且程序可能会或可能不会崩溃,并且守护程序可能会或可能不会飞出用户鼻子。

答案 1 :(得分:0)

void deleteNode(struct node *&head)的代码有很多错误。

  1. 您不检查head是否为nullptr
  2. 您不检查current->next和/或current->prev是否为nullptr
  3. 访问nullptr指针是未定义的行为,这可能意味着崩溃或意外结果或其他。

答案 2 :(得分:0)

尝试使用以下删除功能删除节点。 注意:假设从头部开始删除。

  void deleteNode(struct node *&head,int deleteCount)
  {
        if(head != NULL){
            struct node *current=head; //copy of head.
            struct node *temp,*headPrev,*headNext;
            headPrev = head->prev;
            headNext = head->next;
            int count = 0;
            while(count++ < deleteCount)   
            {
                 //add code to free current node from me
                 temp = current; //get rid of this node
                 currrent = current->next; //skip all the nodes you want delete
            }
            current->prev = headPrev;
            headPrev->next = current;
            head = current;
        }
  }
相关问题