移除链表元素 - 力扣(LeetCode)C语言

203. 移除链表元素 - 力扣(LeetCode)( 点击前面链接即可查看题目)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val)
{
    struct ListNode* cur = head;
    struct ListNode* prev = NULL;
    while(cur)
    {
        if(val == cur->val)
        {
            if(prev == NULL)
            {
                cur = head->next;
                free(head);
                head = cur;
            }
            else
            {
                prev->next = cur->next;
                free(cur);
                cur = prev->next;  
            }
        }
        else
        {
            prev = cur;
            cur = cur->next;  
        }
    }
    return head;
}

你可能感兴趣的:(C语言数据结构练习,链表,leetcode,数据结构)