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 { 11 public: 12 ListNode* removeElements(ListNode* head, int val) 13 { 14 ListNode* dummy = new ListNode(-1); 15 ListNode* pre = dummy; 16 while(head) 17 { 18 if(head->val != val) 19 { 20 pre->next = head; 21 pre = pre->next; 22 } 23 head = head->next; 24 } 25 pre->next = NULL;//必须加 26 return dummy->next; 27 28 } 29 };
来源:https://www.cnblogs.com/yuhong1103/p/12632042.html