题目:
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
解答:
/**
* 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) {
//null处理
if (!head) {
return NULL;
}
//头节点是val单独处理
while (head && head->val == val) head = head->next;
if (!head) {
return NULL;
}
//head不是val
ListNode* tmp = head;
while (tmp->next) {
if (tmp->next->val == val) {
tmp->next = tmp->next->next;
}
else {
tmp = tmp->next;
}
}
return head;
}
};