简体   繁体   English

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

[英]Why I can't append a new node to a LinkedList?

I want to append a new node to a singly LinkedList.我想将一个新节点附加到一个单独的 LinkedList。 This node has data through different classes.该节点具有通过不同类的数据。 Into that I have to add the gathered info from the class Record.为此,我必须添加从类 Record 收集的信息。 I've tried to parse the data for the first node with the code below:我尝试使用以下代码解析第一个节点的数据

Point point = new Point(5.4, 3.2);
Record record = new Record(1, point, 8.2);
System.out.println(list.insert(record));

Then via insert method, I've tried to append the data to the new node:然后通过insert方法,我尝试将数据附加到新节点:

public int insert(Record poi) {
     Node node = new Node(poi);
     node.next = null;
     return nodeCount;
 }

As a result I take zero nodes from the println which means that something doesn't work correctly.结果我从println取零个节点,这意味着某些东西不能正常工作。

All the useful code:所有有用的代码:

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

Any suggestions?有什么建议?

To be inserted in the list, the field first needs to be updated in the insert method which can be done two ways:要插入列表, 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;
}

Your insert method creates new Node objects but does not connect it to neighboring nodes in LinkedList.您的 insert 方法会创建新的 Node 对象,但不会将其连接到 LinkedList 中的相邻节点。 Also, you are not updating nodeCount.此外,您没有更新 nodeCount。

Here is a better version of your insert method:这是插入方法的更好版本:

// 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