力扣203题-移除链表元素

张开发
2026/4/18 18:02:04 15 分钟阅读

分享文章

力扣203题-移除链表元素
一、题目要求给你一个链表的头节点head和一个整数val请你删除链表中所有满足Node.val val的节点并返回新的头节点完成这个算法有两种思路第一种是用头指针指向移除元素的下一个指针达到移除元素效果再返回头指针但是这样有一个问题头指针我们需要额外判断是不是要移除的元素否则将无法移除第一个元素。第二种是创建一个虚拟指针将这个虚拟指针指向头指针这样我们的算法判断如果头指针是要移除的元素就可以使虚拟指针指向头指针的下一个元素这样做的好处是不用额外判断头指针。这两种办法都要创建一个过渡指针将头指针等于过渡指针算法对过渡指针进行操作在结尾再返回头指针。二、代码实现原链表移除元素struct ListNode* removeElements(struct ListNode* head, int val) { while(head ! NULL head-val val){ head head-next; } struct ListNode* cur head; while(cur ! NULL cur-next ! NULL){ if(cur-next-val val){ struct ListNode* temp cur-next; cur-next cur-next-next; free(temp); }else{ cur cur-next; } } return head; }推荐虚拟表头移除元素struct ListNode* removeElements(struct ListNode* head, int val) { struct ListNode* dummy (struct ListNode*)malloc(sizeof(struct ListNode)); dummy-next head; struct ListNode* cur dummy; while(cur-next ! NULL cur-next ! NULL){ if(cur-next-val val){ struct ListNode* temp cur-next; cur-next cur-next-next; free(temp); }else{ cur cur-next; } } head dummy-next; free(dummy); return head; }三、总结理解移除元素原理就可以完成这个代码实现要注意对空指针的判断和分配空间后要用free释放空间

更多文章