LeetCode 203. Remove Linked List Elements

题目

/**
 * 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* term = head;
        ListNode* pre = head;
        
        while(term!=NULL)
        {
            if(term->val == val)
            {
                if(pre == term)
                {
                    head = term->next;
                    pre = head;
                }
                else
                    pre->next = term->next;
            }
            else
            {
                pre = term;
            }
            
            term = term->next;
        }
        
        return head;
        
    }
};
posted @ 2020-02-13 10:08  Shendu.CC  阅读(108)  评论(0编辑  收藏  举报