java插入的链表在结尾处

时间:2015-08-02 16:27:57

标签: nullpointerexception linked-list

伙计我在列表末尾插入新节点时遇到问题。在begening插入工作正常,但在插入结束时它显示空指针异常。

请查看方法inserAtEnd并建议我如何处理它:

package linkedlist;

class Node{
    Node next;
    Object data;
    Node(Object x)
    {
        data=x;
    }
}
class LL
{
    Node first;

    LL(Node f)
    {
       first =f;
    }
    void insertAtBeg(Object x)
    {

        Node n= new Node(x);
        n.next=first;
        first=n;

    }
    void insertAtEnd(Object x)
    {
        Node n= new Node(x);
        Node k;
        k=first;
        while(k!=null)
        {
            k=k.next;
        }

      k.next=n;


    }
    void print()
    {

        Node p=first;
        while(p!=null)
        {

            System.out.print(p.data+"-->");
            p=p.next;
        }
    }

}
public class LinkedList {


    public static void main(String[] args) {
        LL l = new LL(null);
        l.insertAtBeg("Raj");
        l.insertAtBeg("Am ");
        l.insertAtBeg("I ");
        l.insertAtBeg("100 ");
        l.insertAtEnd("Hello");
        l.print();
        System.out.println("returned in main");

    }

}

1 个答案:

答案 0 :(得分:0)

问题是你的循环一直持续到k为空,你想要直到k.next等于null。你也可以通过为最后一个节点设置一个变量来解决它(这几乎总是这样做)。我提供的代码修复了问题,但没有添加任何新变量:

void insertAtEnd(Object x) {
    Node n= new Node(x);
    Node k;
    k=first;

    while(k.next != null) {
        k=k.next;
    }

    k.next=n;
}