链表题
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
思路:
加一个头节点,就比较好操作了
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode newHead(0);
newHead.next = head;
ListNode *temp;
ListNode *cur = &newHead;
while(cur->next != NULL)
{
if(cur->next->val == val)
{
temp = cur->next;
cur->next = cur->next->next;
free(temp);
}
else
cur = cur->next;
}
return newHead.next;
}
};