leetcode 203. Remove Linked List Elements

传送门

203. Remove Linked List Elements

   My Submissions
Total 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

Hide Tags
 Linked List
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 };

 

单链表的插入与删除

原文地址:https://www.cnblogs.com/njczy2010/p/5477499.html