Java编程-循环链表
我正在尝试编写一个 java 类 CircularList,其中包含通常的 Node 内部类和实例变量:
I am trying to write a java class CircularList which contains the usual Node inner class and the instance variables:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,我不会给你该类的完整实现,但我会给你一些建议。
除了循环列表没有结尾这一事实之外,它们与常规列表完全相同,但是您可以在其中找到最后一个项目,如下所示:
节点 tmp = 第一个;
while ( tmp.Next != null )
tmp = tmp.Next;
在循环列表中,想法是这样的:
因为你永远找不到指向空的节点,除非列表为空。最后一个建议是,如果您需要实现索引器,请记住在循环列表中不存在索引超出范围之类的情况,因为
请记住这一点,因此计算这些方法的索引可能会非常棘手。对于正指数,主要思想是:
对于负指数略有不同。我希望我的言语能够帮助到你。如果你想要一个实现,我相信如果你礼貌地询问谷歌,应该有一些:)
祝你好运!
OK, I won't give you the full implementation of the class, but instead I'll give you some advices.
Besides the fact that circular lists have no end, they are quite the same than regular lists, but where you find the last item like this:
Node tmp = first;
while ( tmp.Next != null )
tmp = tmp.Next;
In a circular list the idea is like this:
Because you will never find a node pointing to null, unless the list is empty. One final advice, if you need to implement an indexer, remember that in a circular list there is no such thing as index out of range, because
Keep that in mind, so calculating your index for those methods can be quite tricky. For positive indexes, the main idea is:
For negative ones is slightly different. I hope I can help you with my words. If you want an implementations, I believe that there should be a few if you ask Google politely :)
Best of luck!
我不确定你的问题是什么,你似乎拥有所需的一切。该链表与普通链表之间的唯一区别在于添加到末尾。
在常规链表中,您将创建一个新节点并使最后一个元素指向该节点。在这种情况下,您可以将•Last 节点中的指针更改为指向新节点,并使新节点指向•First。
删除的工作方式与普通链表相同。每当您想要删除一个节点时,您都可以找到哪个其他节点指向该节点(无论是前一个节点,还是在删除第一个节点的情况下,请选中“最后一个”),并使其指向被删除的节点所指向的位置。
如果这不能解决您的问题,请告诉我,我会尽力提供帮助。
刚刚注意到有人已经问了完全相同的问题:
我可以使用 java.util .LinkedList构造循环链表?
I'm not sure what your issue is, you seem to have everything needed. The only difference between that linked list and a normal one would be adding to the end.
In a regular linked list you would create a new node and make the last element point to that node. In this case, you change the pointer in the •Last node to point to the new node, and make the new node point to •First.
Removal works in the same way as a normal linked list. Whenever you want to remove a node, you find which other node points to that one (either previous, or in case of removing the first, check •Last) and make it point to wherever the one being deleted was pointing.
If this does not resolve your issue let me know and I'll try to help.
Just noticed someone has already asked the exact same question:
Can I use java.util.LinkedList to construct a circular/cyclic linked list?
提示...循环列表应该有下一个和上一个而不是第一个和最后一个。逻辑很重要
Hint... circular list should have next and previous instead of first and last. The logic matters