这道题主要考虑的是对链表边界(特殊情况)的检测
P.S.
- 需要注意对于int类型变量来说0和NULL一样
- 在C语言中释放变量内存是free函数,C++是delete
时间和内存消耗以及源代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteNode(struct ListNode* head, int val){
if (head==NULL)
{
return;
}
struct ListNode* Beforedelet = head;
struct ListNode* Tobedelet;
if (Beforedelet->val == val)
{
if (Beforedelet->next == NULL)
{
free(Beforedelet);
Beforedelet = NULL;
}
else
{
Beforedelet->val = Beforedelet->next->val;
Beforedelet->next = Beforedelet->next->next;
}
return Beforedelet;
}
while (Beforedelet->next->val != val)
{
Beforedelet = Beforedelet->next;
}
Tobedelet = Beforedelet->next;
if (Tobedelet->next == NULL)
{
free(Tobedelet);
Beforedelet->next = NULL;
}
else
{
Tobedelet->val = Tobedelet->next->val;
Tobedelet->next = Tobedelet->next->next;
}
return head;
}