c++ - 删除链表的所有其他节点

标签 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

感谢您的帮助。我可以稍后回复以澄清任何误解。

最佳答案

原代码:

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;
}

关于c++ - 删除链表的所有其他节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22164550/

相关文章:

c++ - 计算返回 -1 混淆的 BST 的高度?

c++ - 没有参数列表的模板名称的无效使用

java - 为什么这个在java中反转LinkedList的算法不适合θ(N)?

c - 无法退出 while 循环

java - 为什么我应该使用 Deque 而不是 Stack,使用 LinkedList 而不是 Queue?

c++ - 模板模板参数 - 编译错误

c++ - 在 Visual Studio 中发布版本仍然更慢?

c++ - 多线程上的信号量和临界区问题

c++ - Qt4 小部件 : implementing a wait function without blocking the widget

c - C中基于字符串的链表产生段错误