Total Accepted: 43183 Total Submissions: 160460 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
(E) Remove Element (E) Delete Node in a Linked List
/** * 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) { ListNode* p = head,*next=NULL,*pre=NULL; while(p && p->val==val){ next = p->next; delete(p); p = next; head = p; } while(p){ if(p->val == val){ pre->next = p->next; delete(p); p = pre->next; }else{ pre=p; p=p->next; } } return head; } };
Next challenges: (M) Convert Sorted List to Binary Search Tree (H) Copy List with Random Pointer (E) Intersection of Two Linked Lists
时间: 2024-12-28 12:01:24