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

前端 未结 8 649
有刺的猬
有刺的猬 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:40
    public void addToEnd(Object data){
        Node temp = this;
        while(temp.next!=null)temp=temp.next;
        temp.next=new Node(data, null);
    }
    
    0 讨论(0)
  • 2021-01-16 04:45

    It's a linked list. You either have to

    A) iterate through all your nodes starting at the head, find the last node, then add one.

    or

    B) keep track of the tail, add to the tail, then update tail to the new last node.

    0 讨论(0)
提交回复
热议问题