在Java中的Linked List实现中的任何位置插入一个节点

时间:2015-04-22 02:38:52

标签: java

我已编写此代码,以便在"链接列表"的任何位置插入新节点。

我知道Java中有内置库;我这是把它写成Java的一种做法。

但我收到错误

  

java.lang.NullPointerException

我不知道问题出在哪里。这是我的代码:

 public void insertAtPos(int val , int pos) {

        Node nptr = new Node(val, null);                
        Node current = start;

        /*  Crawl to the requested index */
        for (int i = 0; i < pos; i++){
            current = current.getLink();
        }

        /*  Set the new node's next-node reference to this node's next-node reference  */
        nptr.setLink(current.getLink());

        /*  Set the new node's next-node reference to the new node  */
        current.setLink(nptr);

        size++ ;
  }     

/*  Function to set link to next Node  */
public void setLink(Node n) {
    link = n;
} 

/*  Function to get link to next node  */
public Node getLink() {
    return link;
} 

2 个答案:

答案 0 :(得分:1)

首先,您应该确保pos不大size。其次你的插入算法似乎错了。要抓取到请求的索引,它应该是for (int i = 0; i < pos - 1; i++){,您必须处理pos == 0才能更改起始节点。

答案 1 :(得分:1)

如果你正在使用IDE(我建议你这样做),例如Eclipse,在方法的开头放置一个换行符。如果你不知道如何,你可以看到这个link。然后尝试在调试模式下运行应用程序。通过这个,您可以遍历每个变量并检查它是否包含空值。

此链接可让您更好地理解:here