添加到链表前面
我对如何添加到链接列表的前面感到困惑。
/**
* data is added to the front of the list
* @modifies this
* @ffects 2-->4-->6 becomes data-->2-->4-->6
*/
public void insert(E data) {
if (front == null)
front = new Node(data, null);
else {
Node temp = new Node(data, front);
front = temp;
}
}
这就形成了一个循环。我该如何避免这种情况?
我有一个 LinkedList 类,它在一个名为 front 的变量中保存前端节点。 我在这个 LinkedList 类中有一个 Node 类。
任何帮助将不胜感激。 谢谢。
I am confused as to how to add to the front of the linked list.
/**
* data is added to the front of the list
* @modifies this
* @ffects 2-->4-->6 becomes data-->2-->4-->6
*/
public void insert(E data) {
if (front == null)
front = new Node(data, null);
else {
Node temp = new Node(data, front);
front = temp;
}
}
This creates a cycle. How do I avoid that?
I have a LinkedList class which holds the front Node, in a variable called front.
I have a Node class within this LinkedList class.
Any help would be appreciated.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您无权访问“下一个”节点吗?
在这种情况下
——
Don't you have access to "Next" node ?
In that case
--
我假设 Node 构造函数将 next 指针作为其第二个参数,在这种情况下,我没有看到这段代码有任何明显的错误。这听起来确实像是一个家庭作业问题。如果是,您应该这样标记它。
I'm assuming that the Node constructor takes a next pointer as its 2nd argument, in which case I don't see anything obvious wrong with this code. This really sounds like a homework question. If it is, you should tag it as such.
以我有限的链表知识,我冒昧地说:
您可能想等待有人确认。
With my limited linked list knowledge, I would venture this:
You might want to wait around for somebody to confirm though.
如果没有链表实现的其余代码,就不可能确定,但您提供的代码看起来根本不会创建循环。
如果正在创建一个循环,那么它很可能是在其他地方创建的。或者,您/您的测试将某些其他故障误诊为由循环引起。
如果您需要更多帮助,请发布更多代码/证据......特别是 Node 构造函数,以及让您认为自己有循环的代码。
It is not possible to know for sure without the rest of the code for your linked list implementation, but the code that you have supplied doesn't look like it creates a cycle at all.
If a cycle is being created, it is most likely being created elsewhere. Alternatively, you / your tests are misdiagnosing some other failure as being caused by a cycle.
If you need more help, post more code / evidence ... particularly the Node constructor, and the code that makes you think you have a cycle.
添加一个新节点,如果当前头不为空,则将当前头指向新创建的节点作为下一个节点。
Add a new node and if the current head is not null, then point the current head to the newly created node as the next node.
这是我在Java中将节点插入到链表的前面或头部的实现。
This is my Implementation of Inserting a node to front or head of the Linked List in Java.
一个简单快速[可能效率不高]的解决方案是用新元素创建一个临时的新LinkedList,并将两个列表与前面的临时列表合并在一起。
请参阅下面的示例
A simple and quick [ may not be efficient ] solution is to create a temporary new LinkedList with the new element and merge the two lists together with the temp-list in the front.
see the example below