删除链表中给定值等于val的所有结点

△删除链表中给定值等于val的所有结点
1.无头结点,直接遍历,删除与val相等的结点

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

2.加头结点,好处是不用添加两个指针来记录位置

struct ListNode {
*     int val;
*     struct ListNode *next;
* };
struct ListNode* removeElements(struct ListNode* head, int val)
{
    if(head==NULL)
    {
        printf("链表为空!");
        return NULL;
    }
    ListNode* tmp=new ListNode(0);
    tmp->next=head;
    head=tmp;
    while(tmp->next!=NULL)
    {
        if(head->next->val==val)
        {
            head=head->next->next;
        }
        else
        {
            head=head->next;
        }
        return tmp->next;
}

3.递归
每次对头进行判断,此值是否等于给定值val
如果相等,将此结点删除掉,将下一个结点作为头结点来递归调用自己
否则,将此结点的下一个结点作为头结点来递归调用自己

struct ListNode {
*     int val;
*     struct ListNode *next;
* };
struct ListNode* removeElements(struct ListNode* head, int val)
{
    if(head==NULL)
    {
        printf("链表为空!");
        return NULL;
    }
    else if(head->val==val)
    {
        ListNode *newhead = removeElements(head->next, val);
        free(head);
        return newhead;
    }
    else
    {
        ListNode *newhead = removeElements(head->next, val);
        return head;
    }
}
发布了34 篇原创文章 · 获赞 4 · 访问量 1765

猜你喜欢

转载自blog.csdn.net/qq_41181857/article/details/86579836