打卡。203移除链表元素

本文介绍了如何在C++中删除单链表中的指定值元素,包括直接使用头结点和引入虚拟头结点的两种方法。在直接使用头结点的方法中,首先处理头结点等于目标值的情况,然后遍历链表删除其他匹配的节点。引入虚拟头结点的策略则避免了对头结点的特殊处理,简化了代码逻辑。
摘要由CSDN通过智能技术生成

万事开头难
在这里插入图片描述

1.使用现有链表头结点head

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


struct ListNode* removeElements(struct ListNode* head, int val){
    struct ListNode *temp;
    //当头结点存在并且头结点的值等于val
    while(head && head->val == val){
        temp = head;
        //更新头结点,并删除原来的头结点
        head = head -> next;
        free(temp);
    }
    struct ListNode *cur = head;
    //cur指向头结点
    while(cur && (temp = cur ->next)){
        if(temp->val == val){
            //将cur->next指向cur->next->next并删除cur->next
            cur->next = temp -> next;
            free(temp);
        }
        //若cur->next不等于val,则cur后移
        else cur = cur -> next;
    }
    return head;

}

2.使用虚拟头结点
要想使用虚拟头结点,需要先创建结点,使用malloc

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


struct ListNode* removeElements(struct ListNode* head, int val){
    typedef struct ListNode ListNode;
    ListNode *shead;
    shead = (ListNode*)malloc(sizeof(ListNode));
    //虚拟头结点,要先创建一个结点
    shead->next = head;
    ListNode *cur = shead;
    //cur指向虚拟头结点
    while(cur->next != NULL){
        if(cur->next->val == val){
            ListNode *temp = cur->next;
            cur->next = temp->next;
            free(temp);
        }
     else cur = cur->next;
    }
    head = shead->next;
    free(shead);
    return head;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值