我可以使用 java.util.LinkedList 构造循环链表吗?
我想创建一个循环/循环链表,其中列表的尾部将指向列表的头部。那么我可以使用 java.util.LinkedList 并在创建列表后修改尾节点以使其循环/循环吗?如果是这样,你能给我看一些代码来说明这是如何发生的吗?
如果我不能使用 java.util.LinkedList,我应该如何创建自己的循环/循环链表实现?您能给我展示一下这个实现的框架吗?
如果您需要更多详细信息,请告诉我,我会消除任何困惑。
I would like to create a circular/cyclic linked list where the tail of the list would point back to the head of the list. So can I use java.util.LinkedList
and modify the tail node after creation of the list to make it circular/cyclic? If so, can you show me some code on how that would happen?
If I can't use java.util.LinkedList
, how should I create my own circular/cyclic linked list implementation? Can you show me the skeletons of how this implementation would look?
Let me know if you need more details and I'll clear up any confusion.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
java.util.LinkedList 是集合数据类型之一。集合的目的是提供实用结构,而不是让程序员担心它们的内部实现。如果您必须拥有以某种方式工作的内部结构,而 java.util 内部结构不能保证它们的工作方式,那么它们不适合您。
要实现循环链表,首先创建一个ListNode类:
然后存储一个
ListNode头
,并确保head
的prev
指向“列表的“end”,“end”的“next”指向回“head”。但老实说,保留尾指针的双向链表和循环链表之间没有什么区别。java.util.LinkedList is one of the Collections datatypes. The purpose of Collections is to provide utility structures, not bothering the programmer to worry about their internal implementation. If you must have internals that work in a certain way, and the java.util ones do not guarantee that is how they work, then they are not for you.
To implement a circular linked list, first create a ListNode class:
Then store a
ListNode head
, and make sureprev
ofhead
points to the "end" of the list, andnext
of the "end" points back tohead
. Honestly, though, there's little difference between a bidirectionally linked list keeping a tail pointer and a circular linked list.您可以使用 Deque 使用简单的解决方案。从双端队列中池化最后一个值并将其作为第一个插入。这将导致值的循环旋转
You can use simple solution using Deque. Pool last value from deque and insert it as first. This will cause cyclic roatation of values
对于实际应用(例如,不仅仅是玩耍或学习),我个人更喜欢 Guava 的
Iterables.cycle
方法 - 请参阅Iterables.cycle
For practical application (e.g. not only playing around or learning) I would personally prefer Guava's
Iterables.cycle
method - seeIterables.cycle