【问题标题】:how to insert an array on the node of the linked list如何在链表的节点上插入数组
【发布时间】:2018-12-20 10:57:55
【问题描述】:

我在尝试将字符串数组放在 LinkedList 的节点上时遇到问题,这是我使用的代码。

public class Node { 

    public Node next ; 
    public String[] data;

    public Node (Node next ) {
        this.next = next ;
        this.data = new String[6];
    }
}

这是在LinkedListNode内添加数组的add函数:

public void add() {
    Node current = head;
    if (head == null) {
        for (int i = 0; i < 6; i++) {
            head.data[i] = numData[i];
        }
    } else
        while (current != null) {
            current = current.next;
        }

    for (int i = 0; i < 6; i++) {
        current.data[i] = numData[i];
    }
}

错误:线程“主”java.lang.NullPointerException 中的异常

【问题讨论】:

    标签: java linked-list nodes


    【解决方案1】:

    在您的 add 方法中,current 在最后一个 for 循环中是 null,显然如果 head 是 null,您也会遇到问题。当您想添加新节点时,您似乎忘记了启动新实例。改变你的方法如下:

        public void add()
        {
           Node current = head ; 
           if(head == null ){
               head = new Node(null); //here you need to initiate head
               for(int i = 0 ; i<6 ; i++){
                   head.data[i] = numData[i] ; 
               }
           }
           else {
               while(current.next != null){
               current = current.next ; 
               }
               Node newNode = new Node(null); //initiating a new node
               for(int i = 0 ; i<6 ; i++){
                   newNode.data[i] = numData[i] ;
               }
               current.next = newNode;
           }
        }   
    

    我只是假设您想将数据放入一个新节点中。如果要向最后一个现有节点添加数据,只需更改方法的最后一部分即可。

    【讨论】:

      【解决方案2】:

      需要改变逻辑

      Node current = head ; 
             if(head == null ){
             for(int i = 0 ; i<6 ; i++){
             head.data[i] = numData[i] ;  //here you will get npe beacuse you are using null reference  of head
                }
             }
             else 
             while(current != null){
             current = current.next ; 
             }
             for(int i = 0 ; i<6 ; i++){
                 current.data[i] = numData[i] ;//here you will get npe beacuse you are using null reference  of current
                  }
             }
      

      【讨论】:

        猜你喜欢
        • 2021-05-23
        • 2010-12-31
        • 1970-01-01
        • 2020-05-11
        • 2016-06-28
        • 2018-07-28
        • 1970-01-01
        相关资源
        最近更新 更多