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
比较简单的题目,但是也写错了很多次,因为考虑了很多p = head, q = head, 如果为tail的情况,但其实可以直接加一个前导node在head前面,这样简单很多。
/**
* 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) {
if (head == NULL) return NULL;
ListNode *pre_head = new ListNode(0);
pre_head->next = head; //记得设置pre_head的next
ListNode* pre = pre_head;
ListNode* cur = head;
while (cur) {
if (cur->val == val) {//if else的逻辑要搞清楚
pre->next = cur->next;
cur = pre->next;
}
else {
pre = cur;
cur = cur->next;
}
}
return pre_head->next;// 返回的是pre_head->next, 不是head
}
};