单链表反转(较简单)

单链表反转,自己做了好几种方法,然后到了这种解法,不知道为什么会报错

img


报错内容:引用了空指针,但我不是提前判断了head->next是否为空吗?不理解

img

根本原因,head->next 不为NULL,但是 head->next->next 又可能为 NULL
即使这样,你这个代码也又问题的。你看下我写的:

LNode_t* reverseList(LNode_t* head)
{
    if(!head) {
        return head;
    }
    LNode_t* node = head;
    LNode_t* pre = NULL;
    while(node->next) {
        pre = node->next;
        node->next = pre->next;
        pre->next = head;
        head = pre;
    }
    
    return head;
}

head->next没有判断是否为空。head->next为空的话,head->next->next就会报 引用空指针

简单的可以把这些链表装入vector,然后对vector反向遍历

因为你17行将node->next指向了pre(也就是null),但是此时head等于node同时他们的next都是null,所以在19行时赋值式左右都已经指向null,20行就会报空指针了