繁体   English   中英

为什么我不能将新节点附加到 LinkedList?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM