LeetCode 203. Remove Linked List Elements(移除链表元素) -- c语言

203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example:

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

解题思路:

遍历除head结点之外的结点,并删除值等于val的结点,最后再处理head结点

/*
执行用时 : 24 ms, 在Remove Linked List Elements的C提交中击败了91.56% 的用户
内存消耗 : 9.6 MB, 在Remove Linked List Elements的C提交中击败了73.77% 的用户
*/
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* removeElements(struct ListNode* head, int val){
    
    if(head==NULL)return NULL;

    struct ListNode*p=head->next,*q=head;
    while(p!=NULL){
        if(p->val==val){
            q->next=p->next;
            free(p);
            p=q->next;
        }
        else{
            q=q->next;
            p=p->next;
        }
    }
    if(head->val==val){
        p=head;
        head=head->next;
        free(p);
    }
    return head;
}

一趟遍历所有结点,分三种情况:1、对当前处于第一位且值等于val的结点进行处理,2、对当前不是第一位且值等于val的结点进行处理。3、对值不等于val的结点进行处理

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

struct ListNode* removeElements(struct ListNode* head, int val){
   
    if (head == NULL) {
        return;
    }
    struct ListNode* pPre = NULL;
    struct ListNode* pCur = head;
    while (pCur) {
        if (pCur->val == val) {
            if (pPre == NULL) {//或设置为if(head->val == val)
                head = pCur->next;
                free(pCur);
                pCur = head;
            }
            else {
                pPre->next = pCur->next;
                free(pCur);
                pCur = pPre->next;
            }
        }
        else {
            pPre = pCur;
            pCur = pCur->next;
        }
    } 
    return head;
}

递归法

执行时间60ms
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    
    if(head == NULL ) return head;
    
    head->next =  removeElements( head->next, val);

    if(head->val == val)
    {
        struct ListNode* p = NULL;
        p = head->next;
        free(head);
        head = p;
    }

    return head;
    
}

后记:

应对第一位结点的处理需要特别设置。

点赞