题目描述:
Remove all elements from a linked list of integers that have value val
.
Example
题目思路:
Given 1->2->3->3->4->5->3
, val = 3, you should return the list as1->2->4->5
这题用上dummy head,轻松可解。
Mycode(AC = 27ms):
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head a ListNode
* @param val an integer
* @return a ListNode
*/
ListNode *removeElements(ListNode *head, int val) {
// Write your code here
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *ptr = dummy;
while (ptr->next) {
// if ptr->next is val, then link ptr
// to ptr->next->next, ptr still stays
if (ptr->next->val == val) {
ptr->next = ptr->next->next;
}
else {// ptr goes next
ptr = ptr->next;
}
}
return dummy->next;
}
};