0


【每日一题】移除链表元素(C语言)

移除链表元素,链接奉上
在这里插入图片描述

目录

思路:

正常情况:
下我们移除链表元素时,需要该位置的

前结点与后节点


在这里插入图片描述
特别情况时:
例如在这里插入图片描述

我们发现,需要改变头结点,否则因为返回的

head

因为指向的位置被

free

,会导致程序错误

代码实现:

structListNode*removeElements(structListNode* head,int val){structListNode* prev =NULL;structListNode* cur = head;while(cur)//当cur为NULL时自动结束{if(cur->val == val)//分别判断cur->val的情况{structListNode* next = cur->next;free(cur);if(!prev){//当prev为NULL时改变head
                head = next;}else{
                prev->next = next;}
            cur = next;}else{
            prev = cur;
            cur = cur->next;}}return head;}

链表题目小技巧:

我们调试时可以在VS或其他的软件进行调试,也不用专门搞一个链表:
可以创建一个如下的main函数,根据题目要求进行调试

intmain(){structListNode* n1 =(ListNode*)malloc(sizeof(ListNode));structListNode* n2 =(ListNode*)malloc(sizeof(ListNode));structListNode* n3 =(ListNode*)malloc(sizeof(ListNode));structListNode* n4 =(ListNode*)malloc(sizeof(ListNode));structListNode* n5 =(ListNode*)malloc(sizeof(ListNode));if(!(n1 && n2 && n3 && n4 && n5)){perror("malloc");return-1;}
    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n5;
    n5->next =NULL;

    n1->val =1;
    n2->val =2;
    n3->val =3;
    n4->val =4;
    n5->val =5;return0;}

本文转载自: https://blog.csdn.net/2301_78636079/article/details/134224027
版权归原作者 统一热红茶 所有, 如有侵权,请联系我们删除。

“【每日一题】移除链表元素(C语言)”的评论:

还没有评论