脚本宝典收集整理的这篇文章主要介绍了Day 2 Double pointers in the Linked List,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
I was busy with dealing with something else the other day, but I will continue in this blog from now on :)
This time I will talk about another technique often used in a single-linked-list: double pointers.
For example, when I need to check the nth last element in a linked list, I can use this technique to save memory (instead of creating an entire parallel list)
we will use one pointer to iterate through the entire list, but we’ll also move a second pointer delayed n
steps behind the first one. A count
variable can keep track of the position of the current element in the linked list that the tail pointer is pointing to, which is initially set to 1
which is the first element’s position.
nth last pointer = None tail pointer = linked list head count = 1 while tail pointer exists move tail pointer forward increment count if count >= n + 1 if nth last pointer is None set nth last pointer to head else move nth last pointer forward return nth last pointer
Above is the pseudecode for this approach.
nth last pointer = None tail pointer = linked list head count = 1 while tail pointer exists move tail pointer forward increment count if count >= n + 1 if nth last pointer is None set nth last pointer to head else move nth last pointer forward return nth last pointer
以上是脚本宝典为你收集整理的Day 2 Double pointers in the Linked List全部内容,希望文章能够帮你解决Day 2 Double pointers in the Linked List所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。