[英]Why I can't append a new node to a LinkedList?
我想將一個新節點附加到一個單獨的 LinkedList。 該節點具有通過不同類的數據。 為此,我必須添加從類 Record 收集的信息。 我嘗試使用以下代碼解析第一個節點的數據:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.