//返回值有3种情况,空,头结点,非头结点。
struct ListNode* deleteNode(struct ListNode* head, int val ) {
if(head == NULL)
return NULL; //空链表找个毛线
if(head->val == val)
return head->next; //返回的是非头结点的情况
struct ListNode* pre = head;
struct ListNode* p = head->next;
while(p != NULL){
if(p->val != val){
pre = p; //先移动前驱
p = p->next; //再移动工作结点,否则会断链
}
else{ //找到要找的元素,就跳过该结点,结束
pre->next = pre->next->next;
break;
}
}
return head;
}

京公网安备 11010502036488号