PHP 中的静态变量 - 除了文字和常量之外的东西!
我想创建一个将 LinkNode
附加到给定 LinkList
的函数(创建我自己的 Node
类),但我想添加优化该函数在变量中保存指向最后一个附加节点的指针,因此我所要做的就是将新的 Node
添加到变量的下一个链接。我认为最好的方法是创建一个静态变量
$i = $overallRoot;
,该变量在调用函数 append($node)
时不断更新。 (更新为指向 $node),但显然你只能使函数中的静态变量等于整数等。
实施此优化的最佳方法是什么?感谢您的帮助;刚刚开始学习PHP。
I want to create a function that appends a LinkNode
to a given LinkList
(created my own Node
class), but I want to add the optimization that the function holds in a variable a pointer to the last appended node so all I have to do is add the new Node
to the variable's next link. I thought the best way to do this would be to create a static variable
$i = $overallRoot;
that is constantly updated as the function append($node)
is called. (updated to point to $node), but apparently you can only make static variables in functions equal to ints and such.
What would be the best way to implement this optimization? Thanks for the help; just started learning PHP.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
似乎更稳健的优化是让每个链表跟踪指向它包含的第一个和最后一个节点的指针。这样,无论您上次尝试追加到链表的时间是什么时候,追加到链表的成本都是 O(1)。许多链表都使用这种方法,因为它可以显着加快插入速度。
很抱歉,如果这确实不是您原来问题的答案,但这似乎是获得您正在寻找的结果的更好方法。
It seems like a much more robust optimization would be to have each linked list keep track of a pointer to the first and last node it contains. That way, the cost of appending to a linked list is O(1) regardless of when you last tried appending to it. Many linked lists use this approach, since it can dramatically speed up insertions.
Sorry if this really isn't an answer to your original question, but it seems like a much better way of getting the result you're looking for.