Problem
Remove all elements from a linked list of integers that have value val.
Example
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
static int var = [](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head==NULL)
return head;
while(head->val==val){
if(head->next!=NULL)
head=head->next;
else
return NULL;
}
ListNode* a = head;
while(a!=NULL){
while(a->next!=NULL&&a->next->val==val){
a->next=a->next->next;
}
a=a->next;
}
return head;
}
};
网友评论