单链表头插法逆转,若链表为空时段错误,该怎么解决?
struct ListNode *reverse( struct ListNode *head )
{
struct ListNode *p ,*q, *h;
h=head;
q=p=head->next;
h->next=NULL;
if(head!=NULL)
{
while(p != NULL) {
q=q->next;
p->next = h;
h=p;
p = q;
}
return h;
}
else
return head;
}
q=p=head->next;
如果head为空,就不能执行这行代码了啊。你要在这行代码之前,判断head是否为空,为空直接return head就结束了