力扣_203 移除链表元素

本文详细介绍了力扣上移除链表元素问题的解决思路及C语言实现过程,针对链表头结点为待删除值的情况进行了特别处理,并通过实例演示了如何构建链表并调用移除元素函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1 力扣-移除链表元素

1.1 示例

1.2 思路

1.3 实现


1 力扣-移除链表元素

链接:力扣-移除链表元素

img

1.1 示例

img

1.2 思路

img

但是,如果cur直接等于head,即头值就是val,则prev->next会非法访问(此时prevNULL

img

所以应该这样

img

由于最后返回head,所以这里可以传一级指针

1.3 实现

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

但是,如果遇到这样

img

这里返回NULL,头就是val

如果走读代码+画图还是不懂,直接带入vs里

 struct ListNode {
     int val;
     struct ListNode* next;
 };
 ​
 struct ListNode* removeElements(struct ListNode* head, int val) {
     struct ListNode* prev = NULL;
     struct ListNode* cur = head;
     while (cur)
     {
         if (cur->val == val)
         {
             if (cur == head)
             {
                 head = cur->next;
                 free(cur);
                 cur = head;
 ​
             }
             else
             {
                 prev->next = cur->next;
                 free(cur);
                 cur = prev->next;
             }
         }
         else
         {
             prev = cur;
             cur = cur->next;
         }
     }
     return head;
 }
 int main()
 {
     struct ListNode* newnode1 = (struct ListNode*)malloc(sizeof(struct ListNode));
     struct ListNode* newnode2 = (struct ListNode*)malloc(sizeof(struct ListNode));
     struct ListNode* newnode3 = (struct ListNode*)malloc(sizeof(struct ListNode));
     struct ListNode* newnode4 = (struct ListNode*)malloc(sizeof(struct ListNode));
     newnode1->val = 7;
     newnode2->val = 7;
     newnode3->val = 7;
     newnode4->val = 7;
 ​
     struct ListNode* head = removeElements(newnode1, 7);
   return 0;
 }

上面是题目中代码,下面是自己写的main函数

注意:要自己创建一个链表,就写几个malloc,并赋值,再调用函数

最后调试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值