简体   繁体   中英

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

I want to append a new node to a singly LinkedList. This node has data through different classes. Into that I have to add the gathered info from the class 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:

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.

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:

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. Also, you are not updating 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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