力扣算法Day-5

203.移除链表元素

 给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

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

示例 1: 输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]

示例 2: 输入:head = [], val = 1 输出:[]

示例 3: 输入:head = [7,7,7,7], val = 7 输出:[]

思路:

如果头节点需要删除的话,需要单独写一部分删除头结点的代码逻辑。

或者把malloc一个新的节点,设置为头节点。这样的话就不需要分情况操作了。——虚拟头节点。

直接使用原来的链表来进行移除节点操作: 

struct ListNode* removeElements(struct ListNode* head, int val) {
    struct ListNode* cur;
    struct ListNode* temp;
    // 注意这里不是if
    while (head != NULL && head->val == val) { 
        temp=head;
        head=head->next;
        free(temp);
    }
    cur=head;
    //因为要操作两个节点,所以这两个节点都不能为空
    while (cur&&cur->next) {
        if(cur->next->val==val){
            temp=cur->next;
            cur->next=cur->next->next;
            free(temp);
        }
        else {
            cur=cur->next;
        }
    }
    return head;
}

设置一个虚拟头结点在进行移除节点操作:

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;
    while(cur->next != NULL){
        if (cur->next->val == val){
            ListNode *tmp = cur->next;
            cur->next = cur->next->next;
            free(tmp);
        }
        else{
            cur = cur->next;
        }
    }
    head = shead->next;
    free(shead);
    return head;
}

 

这一期专栏记录将我每天的刷题,希望各位的监督,也希望和各位共勉。

追光的人,终会光芒万丈!!

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小羊没烦恼~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值