我很困惑如何添加到链表的前面。
/**
* 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 类。
如有任何帮助,我们将不胜感激。 谢谢。
最佳答案
您没有访问“下一个”节点的权限吗?
在那种情况下
public void insert(E data) {
if (front == null) {
front = new Node(data, null);
} else {
Node temp = new Node(data, null);
temp.next = front;
front = temp;
}
}
--
class LinkedList {
Node front;
LinkedList() {
front = null;
}
public void AddToFront(String v) {
if (front == null) {
front = new Node(v);
} else {
Node n = new Node(v);
n.next = front;
front = n;
}
}
}
class Node {
public Node next;
private String _val;
public Node(String val) {
_val = val;
}
}
关于java - 添加到链表前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4882857/