“路虽远,行则将至”
❤️主页:小赛毛
☕今日份刷题:移除链表元素
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例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 输出:[]
题目分析:
这里需要注意一点的是:在oj题目里面如果没有提到带哨兵位,则默认为不带头结点的链表。
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * struct ListNode *next;
- * };
- */
-
-
- struct ListNode* removeElements(struct ListNode* head, int val)
- {
- struct ListNode* prev = NULL, *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;
- }
现在,我们再来考虑一种解法:
遍历原链表,把不是val的节点,尾插到新链表
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * struct ListNode *next;
- * };
- */
-
-
- struct ListNode* removeElements(struct ListNode* head, int val)
- {
- struct ListNode* cur = head;
- struct ListNode* newhead = NULL,*tail = NULL;
-
- while(cur)
- {
- if(cur->val == val)
- {
- //删除
- struct ListNode* 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;
- return newhead;
- }