Remove Linked List Element
题目:
Remove all elements from a linked list of integers that have value val.
分析:
简单题目没啥好分析的,画画图,验证验证,保证别出错,一次通过就好了。
解法:
class Solution {
public:
/**
* @param head a ListNode
* @param val an integer
* @return a ListNode
*/
ListNode *removeElements(ListNode *head, int val) {
// Write your code here
if (head == NULL) {
return head;
}
ListNode dummy(val - 1);
dummy.next = head;
ListNode* prev = &dummy;
ListNode* curr = head;
while (curr != NULL) {
if (curr->val == val) {
curr = curr->next;
prev->next = curr;
} else {
prev = prev->next;
curr = curr->next;
}
}
return dummy.next;
}
};