指定一个值,移除所有链表上是这个值的节点。需要注意头指针也有值,注意头指针为空的情况。
/**
* 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
ListNode *p;
ListNode *q;
while(head!=NULL&&head->val == val){
head = head->next;
}
if(head == NULL)
return head;
p = head;
q = head->next;
while (q!=NULL){
if(q->val == val){
p->next = q->next;
delete q;
q = p->next;
}
else{
p = p -> next;
q = q -> next;
}
}
return head;
}
};