OJ. Delete the specified node of the linked list

Given the head pointer of the singly linked list and the value of a node to be deleted, define a function to delete the node.
Return the head node of the deleted linked list.

Example 1:
Input: head = [4,5,1,9], val = 5
Output: [4,1,9]
Explanation: Given the second node with a value of 5 in your linked list, then you are called After the function, the linked list becomes 4 -> 1 -> 9.

Idea: Double pointer. Cur is defined as the node to be deleted, prev is the node before cur, cur goes all the way back from the head, after finding the node to be deleted, make prev->next=cur->next, and then release cur.

struct ListNode* deleteNode(struct ListNode* head, int val)
{
    
    
    //cur定义为head,prev定义为NULL;
    struct ListNode*cur=head;
    struct ListNode*prev=NULL;
    //特殊条件判定
    if(head==NULL)
    {
    
    
        return NULL;
    }
    //特殊条件判定,如果头节点为要删除的节点
    if(head->val==val)
    {
    
    
        return head->next;
    }
    //让prev等于cur之后的节点,cur为要删除的节点;
    while(cur&&cur->val!=val)
    {
    
    
        prev=cur;
        cur=cur->next;
    }
    //删除cur;
    if(cur)
        {
    
    
            prev->next=cur->next;
            free(cur);
        }
    return head;
}

Guess you like

Origin blog.csdn.net/qq_43745617/article/details/111906785