想用92题解的方法(类似于left= 0, right =length),
执行出错信息:( while(cur.next != null) { 这句)
Line 22: java.lang.NullPointerException
请问用这种方法的话 可以怎么修改?多谢
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
// 设置 dummyNode 是这一类问题的一般做法
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode;
// for (int i = 0; i < left - 1; i++) {
// pre = pre.next;
// }
ListNode cur = pre.next;
ListNode next;
while(cur.next != null) {
// for (int i = 0; i < right - left; i++) {
next = cur.next;
cur.next = next.next;
next.next = pre.next;
pre.next = next;
}
return dummyNode.next;
}
}
你这个思路有问题。建议你再好好思考思考,用纸笔模拟一下你的过程。
报错原因是因为,你的pre是 head 的next ,cur是per的next, 当只有一个元素的时候,pre.next = null,这时你的cur.next 就会报错,因为你取了head.next.next
在理一理思路,这个思路不对,在思考思考