203. Remove Linked List Elements

2018-07-19  本文已影响0人  SilentDawn

Problem

Remove all elements from a linked list of integers that have value val.

Example

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if(head==NULL)
            return head;
        
        while(head->val==val){
            if(head->next!=NULL)
                head=head->next;
            else
                return NULL;
        }
        ListNode* a = head;
        while(a!=NULL){
            while(a->next!=NULL&&a->next->val==val){
                a->next=a->next->next;
            }
            a=a->next;
        }
        return head;
    }
};

Result

203. Remove Linked List Elements.png
上一篇下一篇

猜你喜欢

热点阅读