美文网首页
203. Remove Linked List Elements

203. Remove Linked List Elements

作者: SilentDawn | 来源:发表于2018-07-19 23:19 被阅读0次

    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

    相关文章

      网友评论

          本文标题:203. Remove Linked List Elements

          本文链接:https://www.haomeiwen.com/subject/zfixmftx.html