Java - add a node to the end of a list?

前端 未结 8 654
有刺的猬
有刺的猬 2021-01-16 03:55

Here\'s what I have:

public class Node{
    Object data;
    Node next;

    Node(Object data, Node next){
        this.data = data;
        this.next = next         


        
8条回答
  •  广开言路
    2021-01-16 04:31

    Start from the head:

    Node currentNode = headNode;
    while (node.getNext() != null) {
       currentNode = currentNode.getNext();
    }
    
    currentNode.setNext(newNodeForInsertion);
    

    A faster way is to store the last node of the list somewhere so you don't have to go through the whole list.

提交回复
热议问题