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 --> 5
遍历链表,记当前遍历的链表结点为p,若p->val == val,则删除该结点,删除结点分两种情况:
1)删除的是头结点,直接将头指针后移;
2)删除的是其它结点,那么需要将p结点的前一个节点pre的next修改为p的next。然后再将p指向此时pre的next结点。
/**
* 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 *p = head;
ListNode *pre = head;
while(p){//p为要删除的结点
if(head -> val == val){
head = head -> next;
free(p);
p = head;
pre = head;
continue;
}
if(val == p -> val){
pre -> next = p -> next;
free(p);
p = pre -> next;
continue;
}
pre = p;
p = p -> next;
}
return head;
}
};