C ++循环链表:删除元素

时间:2013-08-21 18:02:42

标签: c++ pointers linked-list circular-list

我已完成插入,在循环链接列表中搜索但是为了删除我收到编译器错误...

以下是我的节点结构。

 struct node
 {
     int               p_data;
     struct node*   p_next;

     node(node* head, int data)
     {
           p_next = head;
           p_data = data;
     }

     explicit node(int data)
      {
           p_next = nullptr;
           p_data = data;
      }
 };




 node* remove_circular(node* head, node* target)
 {
      if (head == target->p_next)
      {
           delete head;
           return nullptr;
      }

      auto next_pointer = target->p_next;
      target->p_data = next_pointer->p_data;
      target->p_next = next_pointer->p_next;

      delete target->p_next;
      return target;
 }

在主要功能中我打电话

 head = remove_circular(head, head);
 head = remove_circular(head, temp);

这是删除head元素和temp指向的另一个元素。 但我收到错误

任何人都有任何想法从循环列表中删除一个元素??

我将其更改为删除target-> p_next; 但现在它删除了列表中的所有内容。 任何想法???

3 个答案:

答案 0 :(得分:4)

这是循环链表的工作方式:


linked list example


每个节点指向下一行,列表的尾部指向标题节点。这是从circular linked listregular linked list的差异(在上面的情况下,会使 37 指向终结符null)。

如果您的列表只有一个对象,那么它应该如下所示:


only node situation


因此,正如您所看到的,没有任何对象指向null的任何位置,但它会在您的代码中使用explicit构造函数(如果我写node n = node(12)将会运行) 。

我建议您查看this link,以便更好地了解算法的外观。

答案 1 :(得分:2)

解决编译错误后,您仍会遇到算法问题。我建议你在纸上画一个圆形列表,并考虑删除元素所需的步骤。考虑所有情况,例如:空列表,1个项目的列表,不在列表中的元素等等。

答案 2 :(得分:1)

你需要考虑几件事。

1。)空列表的情况

  if(head == nullptr){//Empty list case
      return nullptr;
  }

2。)要删除的目标是头节点,这是列表中唯一的节点。

  if (head == target && target->p_next == head){
       create a temp node with the data value of target
       target = nullptr;//Since nothing points to target now it is for all intents and purposes deleted from the list but the data is still there so you can do something with it. I assume this is necessary because you return a node *.
       return the temp node
  }

3。)创建一个遍历整个列表的循环。如果您有两个项目列表且目标是第二个项目,那么您只能删除下一个有效的节点。

  auto next_pointer = head->p_next;//could not be target->p_next as this assumed 
  while (next_pointer->p_next != target){//This while loop traverses the list rather than just deleting the next entry.

4.)在你循环中添加一个检查以查看是否已遍历列表并且从未找到目标。

   if (next_pointer->p_next == head){
      return nullptr;
   }//end IF

5.。)在循环内添加else case,这意味着target位于列表中的任意位置。由于我给了你剩下的部分,我会留下你来获取这部分内容。只比上述陈述长几行并不难。

相关问题