LeetCode Remove Linked List Elements

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

  题目:要求你把一个链表中所有值等于val的结点删除

这个题目要设置一个辅助变量来保存正在遍历的结点的前一个结点,这样你就可以进行删除操作了

/**
 * 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) {
        if(!head)return head;
        ListNode * temp=head,*pre;
        pre->next=temp;
        for(;temp->next;)
        {
            if(val==temp->val)
            {
            temp->val=temp->next->val;
            temp->next=temp->next->next;
            }
            else
            {
                pre=pre->next;
                temp=temp->next;
            }
        }
        if(val==temp->val)
        if(pre->next==head)//如果pre的next指向head,说明链表中的结点的值全部是val,返回NULL
        return NULL;
        else pre->next=NULL;//否则,pre的next指向NULL即可
        return head;
    }
};
原文地址:https://www.cnblogs.com/csudanli/p/5343494.html