我想将一个新节点附加到一个单独的LinkedList中。此节点具有通过不同类的数据。我必须添加从课堂记录中收集的信息。我已经尝试用解析第一个节点的数据,下面的代码是:
Point point = new Point(5.4, 3.2);
Record record = new Record(1, point, 8.2);
System.out.println(list.insert(record));
然后通过insert
方法,我尝试将数据附加到新节点:
public int insert(Record poi) {
Node node = new Node(poi);
node.next = null;
return nodeCount;
}
因此,我从println
中获取了零个节点,这意味着有些东西不能正常工作。
所有有用的代码:
class Node {
public Record poi;
public Node next;
public Node(Record poi) {
this.poi = poi;
}
}
class RankList {
private Node first;
private int nodeCount;
private Record record;
public static void main(String[] args) {
RankList list = new RankList();
Point point = new Point(5.4, 3.2);
Record record = new Record(1, point, 8.2);
System.out.println(list.insert(record));
}
public RankList() { }
public int insert(Record poi) {
Node node = new Node(poi);
node.next = null;
return nodeCount;
}
有什么建议吗?
要插入列表中,需要在插入方法中更新字段first
,这可以通过两种方式完成:
public int insertBeforeFirst(Record poi) {
Node node = new Node(poi);
node.next = first;
first = node;
return ++nodeCount;
}
public int insertAfterFirst(Record poi) {
Node node = new Node(poi);
node.next = null;
if (null == first) {
first = node;
} else {
node.next = first.next;
first.next = node;
}
return ++nodeCount;
}
您的insert方法会创建新的Node对象,但不会将其连接到LinkedList中的相邻节点。此外,您没有更新nodeCount。
这里有一个更好的插入方法版本:
// It also takes in a Node object reference which is one previous to the new Node
public int insert(Record poi, Node node)
{
if (node == null)
{
//if the node is null we assume LinkedList is empty
node = new Node(poi);
first = node;
}
else
{
//inserting new node in between 2 nodes
Node nextRef = node.next;
node.next = new Node(poi);
node.next.next = nextRef;
}
//updating node count
nodeCount++;
return nodeCount;
}