题目链接
题目解析
这道题并不是很难,这里只阐释再利用递归完成时的一个细节问题。
//1.0 version
class Solution {
public ListNode reverseList(ListNode head) {
if(head.next==null) return head;
ListNode temp=reverseList(head.next);
head.next.next=head;
head.next=null;
return temp;
}
}
看起来并没有什么问题,再提交时,却报了空指针异常错误,思考后,发现是少考虑了head=null
的情况,进行改进
//2.0version
class Solution {
public ListNode reverseList(ListNode head) {
if(head.next==null||head==null) return head;
ListNode temp=reverseList(head.next);
head.next.next=head;
head.next=null;
return temp;
}
}
添加了head==null
的情况,却还是产生了错误,且同样的是空指针异常,思考后,发现是if语句的编写顺序产生了问题,
if(head.next==null||head==null) return head;
这一句代码看似考虑了head为空的情况,但由于head==null
写在后面,在判断时,还是会先执行head.next==null
的判断,当head为空时,执行head.next判断,产生异常,结束程序执行。
//3.0version
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode temp=reverseList(head.next);
head.next.next=head;
head.next=null;
return temp;
}
}
下面是迭代解法:
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode pre=null;
ListNode temp=head;
while(temp!=null){
ListNode p=temp;
temp=temp.next;
p.next=pre;
pre=p;
}
return pre;
}
}