- Remove Linked List Elements My Submissions QuestionEditorial Solution
Total Accepted: 61924 Total Submissions: 215788 Difficulty: Easy
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
思路:先找到第一个不等于指定值的首节点,作为返回值
另外在过程中过滤掉等于val值的节点并使前面一个不为val值得节点指向下一个不为val值的节点
时间复杂度:O(n)
空间复杂度:O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head==NULL)return NULL;
while(head!=NULL&&head->val==val)head=head->next;//找到第一个头部
ListNode *p=head,*prep=head;
while(p!=NULL){
prep=p;
p=p->next;
while(p!=NULL&&p->val==val)p=p->next;//直到找到下一个不为val的节点并指向它
prep->next = p;
}
return head;
}
};