力扣:203. 移除链表元素

203. 移除链表元素
在这里插入图片描述

方法一:
//设置 虚拟头节点 方法
struct ListNode* removeElements(struct ListNode* head, int val)
{
    
    
    typedef struct ListNode ListNode;
    ListNode* shead=(ListNode*)malloc(sizeof(ListNode));
    shead->next=head;
    ListNode* cur=shead;
    while(cur->next != NULL)
    {
    
    
        if(cur->next->val==val)
        {
    
    
            ListNode *tmp = cur->next;
            cur->next=tmp->next;
            free(tmp);
        }
        else cur=cur->next;
    }
    head=shead->next;
    free(shead);
    return head;
}
方法二:普通法
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val)
{
    
    
    struct ListNode* tmp;
    while(head && head->val==val)
    {
    
    
        tmp=head;
        head=head->next;
        free(tmp);
    }

    struct ListNode* cur=head;
    while(cur && (tmp=cur->next))
    {
    
    
        if(tmp->val==val)
        {
    
    
            cur->next=tmp->next;
            free(tmp);
        }
        else cur=cur->next;
    }
    return head;

}

猜你喜欢

转载自blog.csdn.net/congfen214/article/details/129538883