203. Remove Linked List Elements
My SubmissionsTotal Accepted: 62648 Total Submissions: 217789 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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Show Similar Problems
题解:
转自:
Submission Details
63 / 63 test cases passed.
|
Status:
Accepted |
Runtime: 32 ms
|
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeElements(ListNode* head, int val) { 12 ListNode* dummy = new ListNode(0); 13 dummy->next = head; 14 ListNode *p = dummy; 15 ListNode *q = head; 16 while(q != NULL) { 17 if(q->val == val) { 18 p->next = q->next; 19 free(q); 20 } 21 else { 22 p = p->next; 23 } 24 q = q->next; 25 } 26 return dummy->next; 27 } 28 };