问题描述
提示:这里描述项目中遇到的问题:
对单向链表进行反转,代码:
@Override
public static Node reverseLinkedList2(Node head) {
Node pre = null;
Node next = null;
next = head.next;
while(head.next != null){
head.next = pre;
pre = head;
head = next;
next = head.next;
}
head.next = pre;
return head;
}
报错信息:
Exception in thread “main” java.lang.NullPointerException
网上搜了搜,基本就是建议我声明next和pre指针的时候进行初始化,即pre = new Node()但是由于我给Node的定义是Node的value部分必须为int,而这个地方我需要将pre指向null,这就会变得非常麻烦。
原因分析:
提示:这里填写问题的分析:
这个地方报的这个错可以理解为在链表为某种情况下,调用了null的next而导致的报错,仔细考虑会发现如果head一开始指向的就是null,这个代码就一定会报错
解决方案:
提示:这里填写该问题的具体解决方案:
正确代码:
public static Node reverseLinkedList2(Node head) {
if(head == null){
return head;
}
Node pre = null;
Node next = null;
next = head.next;
while(head.next != null){
head.next = pre;
pre = head;
head = next;
next = head.next;
}
head.next = pre;
return head;
}