Remove all elements from a linked list of integers that have value val.
/** * 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* dummy = new ListNode(0); dummy->next = head; while(head!=NULL && head->val == val) { head = head->next; dummy->next = head; } if(head==NULL) return NULL; while(head->next!=NULL) { if(head->next->val == val) head->next = head->next->next; else head=head->next; } return dummy->next; } };
No comments:
Post a Comment