为什么我不能将一个新节点附加到linkedlist?

xqnpmsa8  于 2021-07-11  发布在  Java
关注(0)|答案(2)|浏览(192)

我想在单个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;
    }

有什么建议吗?

gcmastyq

gcmastyq1#

要插入列表中,字段 first 需要在insert方法中进行更新,可以通过两种方式进行更新:

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;
}
mwkjh3gx

mwkjh3gx2#

插入方法创建新的节点对象,但不将其连接到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;
}

相关问题