删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
C++1
/**
* 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) {
ListNode* h = new ListNode(0);
h->next = head;
if(!head){
return NULL;
}
while(h->next&&h->next->val == val){
head = h->next->next;
h->next = head;
}
while(h&&h->next){
if(h->next->val == val){
h->next = h->next->next;
}else{
h = h->next;
}
}
return head;
}
};
网友评论