LeetCode:Remove Linked List Elements
Problem:
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->5Solution:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeElements(ListNode* head, int val) { 12 13 if(head==NULL) return NULL; 14 ListNode dummy(-1); 15 ListNode *p=&dummy; 16 p->next=head; 17 ListNode *newhead=p; 18 19 while(p!=NULL) 20 { 21 if(p->next!=NULL) 22 { 23 if(p->next->val==val) 24 { 25 ListNode *temp=p->next; 26 p->next=temp->next; 27 delete temp; 28 29 if(p->next!=NULL&&p->next->val!=val) 30 p=p->next; 31 else 32 continue; 33 } 34 else 35 p=p->next; 36 37 } 38 else 39 break; 40 } 43 return newhead->next; 44 } 45 };