What is the pointer-to-pointer technique for the simpler traversal of linked lists?(用于更简单地遍历链表的指针指向技术是什么?)
问题描述
十年前,有人向我展示了一种遍历链表的技术:您使用了双指针(pointer-to-pointer)而不是单指针.
该技术无需检查某些边界/边缘情况,从而生成更小、更优雅的代码.
有人知道这个技术到底是什么吗?
我认为你的意思是双指针,就像指向一个指针的指针"一样,这对于在单向链表的末尾插入非常有效
strong> 或树结构.这个想法是,一旦找到结尾(空指针),您就不需要特殊情况或尾随指针"来跟随您的遍历指针.因为您可以将指针取消引用到要插入的指针(它指向 到最后一个节点的下一个指针!).像这样:
T **p = &list_start;而 (*p) {p = &(*p)->next;}*p = 新 T;
而不是这样的:
T *p = list_start;如果(p == NULL){list_start = 新 T;} 别的 {而(p->下一个){p=p->下一个;}p->next = 新 T;}
注意:它对于为单向链表制作有效的删除代码也很有用.在任何时候执行 *p = (*p)->next
都会删除您正在查看"的节点(当然您仍然需要清理节点的存储).
Ten years ago, I was shown a technique for traversing a linked list: instead of using a single pointer, you used a double pointer (pointer-to-pointer).
The technique yielded smaller, more elegant code by eliminating the need to check for certain boundary/edge cases.
Does anyone know what this technique actually is?
I think you mean double pointer as in "pointer to a pointer" which is very efficient for inserting at the end of a singly linked list or a tree structure. The idea is that you don't need a special case or a "trailing pointer" to follow your traversal pointer once you find the end (a NULL pointer). Since you can just dereference your pointer to a pointer (it points to the last node's next pointer!) to insert. Something like this:
T **p = &list_start;
while (*p) {
p = &(*p)->next;
}
*p = new T;
instead of something like this:
T *p = list_start;
if (p == NULL) {
list_start = new T;
} else {
while (p->next) {
p = p->next;
}
p->next = new T;
}
NOTE: It is also useful for making efficient removal code for a singly linked list. At any point doing *p = (*p)->next
will remove the node you are "looking at" (of course you still need to clean up the node's storage).
这篇关于用于更简单地遍历链表的指针指向技术是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于更简单地遍历链表的指针指向技术是什么?


基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01