【 LeetCode题解 】203. 移除链表元素
题目链接 : https://leetcode.cn/problems/remove-linked-list-elements/
关注博主,后期持续更新系列文章
***感谢观看,希望对你有所帮助***
目录
🌟题目要求
🌟解题思路(动图解析)
🧐方案一
方案1:主要思路遇到val就删除,分为头删和中间删除两种情况。
当val在链表中间时,遇到val就删除链表中和val相同的节点,并链接val后面的节点。
当val在链表开头时,或者连续的时候,我们将链表其实的head(头)向后移动,直到找到不是val的节点,作为开始的头。
😁方案二
方案2:遍历原链表,把不是val的节点,尾插到新链表
使用尾插的方法,将不是val的值插入到新链表,为了避免增加时间复杂度,使用tail为尾节点
但需要注意的是当末尾不是val值时需要将tail->next置为NULL
🌟代码示列
方案一 代码:
structListNode*removeElements(structListNode*head, intval) { structListNode*prev=NULL; structListNode*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; } } returnhead; }
方案二 代码:
structListNode*removeElements(structListNode*head, intval) { structListNode*cur=head; structListNode*newhead=NULL; structListNode*tail=NULL; while(cur) { if(cur->val==val) { structListNode*del=cur; cur=cur->next; free(del); } else { if(tail==NULL) { newhead=tail=cur; } else { tail->next=cur; tail=tail->next; } cur=cur->next; } } if(tail) tail->next=NULL; returnnewhead; }



