删除链表中等于给定值val的所有节点。
样例
给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。
/**
* 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
if(head==NULL) return head;
ListNode *p=new ListNode(0);
p->next=head;
head=p;
ListNode *r=head;
ListNode *q=r->next;
while(q){
if(q->val==val){
p->next=q->next;
q=p->next;
}else{
p=q;
q=q->next;
}
}
head=head->next;
return head;
}
};
我每天都在努力,只是想证明我是认真的活着.


浙公网安备 33010602011771号