我很困惑如何添加到链表的前面.
/**
* 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;
}
}
Run Code Online (Sandbox Code Playgroud)
这创造了一个循环.我该如何避免?
我有一个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;
}
}
Run Code Online (Sandbox Code Playgroud)
-
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;
}
}
Run Code Online (Sandbox Code Playgroud)
以我有限的链表知识,我冒昧地说:
Node temp = new Node(data);
temp.next = front;
front = temp;
Run Code Online (Sandbox Code Playgroud)
不过,您可能想等待有人确认。
| 归档时间: |
|
| 查看次数: |
45480 次 |
| 最近记录: |