消除搜索链表中的 NULL 检查
如何消除搜索链表的 while 循环每次迭代中的 NULL 检查?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何消除搜索链表的 while 循环每次迭代中的 NULL 检查?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
您可以使用哨兵元素 - 附加您搜索的元素。如果发现哨兵返回未找到;在这两种情况下删除哨兵。
补充:
参见哨兵搜索示例;我对语言表示歉意。我记得N。 Wirth 的“算法和数据结构”;我对语言表示歉意。
You could use a sentinel element - append the element you search. If you found the sentinel return not found; remove the sentinel in both cases.
Added:
See Sentinel search example; my apology for the language. I remembered the strategy from N. Wirth's "Algorithmen und Datenstrukturen"; my apologies for the languages.
你根本做不到。
只要您迭代任何数据结构,您总是希望您的算法在到达结构末尾时采取不同的行为,从而需要进行任何类型的检查。无论您的数据结构是什么,这都是正确的,并且不依赖于您迭代的“方式”: for(int i = 0 ; i < sizeArray ; ++i), for(iterator it = myList.begin() ; it != mylist.end(); it++), while(currentNode.hasChildren()), while(javaIterator.hasNext( )) ...
然而,无论您的循环做什么,检查可访问对象是否为 NULL 永远不会成为算法的瓶颈。甚至很难减少耗时...
避免检查的唯一方法是避免循环本身,因此将每个步骤写入循环中,但它要求您知道链表的大小编译时间,在这种情况下,您的编译器可能比您自己更好地优化了您的代码;-)
You simply can't.
As long as you are iterating over any data structure, you always want your algorithm to act differently IF it has reached the end of the structure thus requiring any kind of check. That is true whatever your data structure is and does not depend on the "way" you are iterating: for(int i = 0 ; i < sizeArray ; ++i), for(iterator it = myList.begin() ; it != mylist.end(); it++), while(currentNode.hasChildren()), while(javaIterator.hasNext()) ...
Nevertheless, whatever your loop does, checking if an accessible object is NULL will never be the bottleneck of your algorithm. It is even difficult to do less time consuming...
The ONLY way you could possibly avoid the check would be to avoid the loop itself, therefore writing each step underlying in the loop but it requires you to know the size of the linked list at compile time and in that case your compiler may have optimized your code better than you would probably have done yourself ;-)
您可以使用循环(循环)链表,其中最后一个元素与第一个元素链接。
You can use a circular (looping) linked list where the last element is linked with the first one.
您可以跟踪列表中的元素数量。如果您始终知道列表中有多少个元素以及当前位于哪个位置,那么当您想要前进到下一个元素时,无需检查
NULL
。You could keep track of the number of elements in your list. If you always know how many element are in the list and at which position you currently are, then there is no need to check for
NULL
when you want to advance to the next element.