【leetcode】Remove Duplicates from Sorted List

来源:互联网 发布:php ll 和 优先级 编辑:程序博客网 时间:2024/06/05 22:25
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *deleteDuplicates(ListNode *head) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(head==NULL||head->next==NULL)            return head;                ListNode *dummy = new ListNode(0);        dummy->next=head;                ListNode *pre=dummy;        ListNode *cur=dummy->next;                bool needDelete=false;        while(cur!=NULL&&cur->next!=NULL)        {            if(cur->val==cur->next->val)                needDelete=true;            else            {                if(needDelete)                {                    pre->next=cur;//dif from [Remove Duplicates from Sorted List II]                    pre=cur;//dif from [Remove Duplicates from Sorted List II]                    needDelete=false;                }                   else                {                    pre=cur;                }            }            cur=cur->next;        }        if(needDelete)            pre->next=cur;//dif from [Remove Duplicates from Sorted List II]        return dummy->next;    }};

原创粉丝点击