我正在尝试从链接列表的末尾返回第N个节点,但是遇到错误。所以这就是我到目前为止所得到的:
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class LinkedList {
Node head;
Node tail;
public LinkedList() {
head = tail = null;
}
public boolean isEmpty(){
return head==null;
}
public void insertFirst(int data) {
Node newLink = new Node(data);
if (head == null) {// list is empty
tail = newLink;
}
newLink.next = head;
head = newLink ;
}
public Node nthFromLast(Node node, int n){
for (int i = 0; i < n; i++) {
if (head == null) {
return null;
}
tail = tail.next;
}
while (head.next != null) {
head = head.next;
tail = tail.next;
}
return tail;
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
Node node = new Node(4);
list.insertFirst(16);
list.insertFirst(23);
list.insertFirst(55);
list.nthFromLast(node, 3);
}
}
I'm getting a NullPointerException
for some reason and I can't figure it out. I'd love for someone to point out my error in the code so I could understand the subject better.
Try stepping through the code through a debugger and see what happens. When the first node is added, you set
tail
to the first item. It doesn't get changed untilnthFromLast
(in the first for loop of that method), but its pointing to the last node in the list. Now consider the first iteration (or wheni=0
). Tail is still pointing to the last node in the list. But since it is the last node,tail.next
isnull
, so it setstail
tonull
and then you get the NPE when the loop tries to executetail.next
.