删除链表的每个其他节点

时间:2014-03-04 06:28:17

标签: c++ linked-list

我搜索了之前提出的问题,但找不到我想要的内容。如果有人知道如何删除链表的每个其他节点,我很好奇。我有一个名为duplicate的函数,它将1 2 3转换为1 1 2 2 3 3。删除每个其他节点都可以正常工作,无需比较它们或任何东西。如果有人有任何见解。请不要只发布源代码。

这是我试图做的但是没有工作。

Node *current;
Node *undo;
for (current = front, undo = current->next->next; 
undo != NULL; current = current->next, undo = current->next->next){
    current->next = undo;
}

这将输出1 1 2 2 3 3 3

感谢您的帮助。我可以稍后发表评论,澄清任何误解。

2 个答案:

答案 0 :(得分:1)

原始代码:

for (current = front, undo = current->next->next; 
   undo != NULL; 
   current = current->next, // this moves current on before you use it's next pointer
   undo = current->next->next){
     current->next = undo;
}

要解决此问题,请不要取消分配不需要的节点(假定节点数为偶数):

for (current = front;  current != NULL; current = current->next){
      current->next = current->next->next
}

处理奇数长度列表,并删除已删除节点的内存:

for (current = front;  current && current->next ; current = current->next){
      undo = current->next;
      current->next = current->next->next
      delete undo;
}

答案 1 :(得分:0)

如果需要,我会使用std::list(或者std::forward_list)和C ++ 11中的std::copy_ifstd::remove_if

否则,请记住要修改的指针的地址,如:

Node**undoad = &front;
int cnt=0;
for (current=front; current != NULL; current=current->next) {
  if (cnt%2 == 1) {
    Node*undo = *undoad;
    undoad = &current->next; 
    if (undo) undo->next = current->next;
  }
  cnt++;
}

但是,以上可能是memory leak:您可能需要在某处使用delete