uup_lmm 2021-03-07 17:14 采纳率: 87.5%
浏览 79
已结题

leetcode 206反转链表,用了类似92的题解,报错空指针异常

想用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;
    }
}
  • 写回答

2条回答 默认 最新

  • 三岁丫 2021-03-07 19:47
    关注

    你这个思路有问题。建议你再好好思考思考,用纸笔模拟一下你的过程。

    评论

报告相同问题?