"Leetcode" 203. Remove linked list elements

Title description

Delete all nodes in the linked list that are equal to the given value val.

Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

Language : C language
thinking analysis

  • Give two pointers cur and prev, prev is the pointer before cur
  • Find the node whose val value is equal to the input val value in the linked list. If the first node needs to be deleted, let the head pointer point to the next node head=cur->next, delete the first node free(cur), and then Let cur=head
  • If the node to be deleted is not the first node found, let prev->next=cur->next, delete the node free(cur), and then let cur=prev->next.

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

typedef struct ListNode Node;//后面只需要使用Node*

struct ListNode* removeElements(struct ListNode* head, int val)
{  
    Node* cur=head;
    Node* prev=NULL;

    while(cur)
    {
        if(cur->val==val)
        {
            if(cur == head)//删除的节点是第一个节点
            {
                head=cur->next;
                free(cur);
                cur=head;
            }
            else//删除非第一个节点
            {
                prev->next=cur->next;
                free(cur);
                cur=prev->next;
            }
        }
        else
        {
            prev=cur;
            cur=cur->next;
        }
    }
    return head;
}

operation result
Insert picture description here

Guess you like

Origin blog.csdn.net/NanlinW/article/details/104759194