【leetcode】Remove Duplicates from Sorted List II

来源:互联网 发布:网络诈骗教育考试题库 编辑:程序博客网 时间:2024/04/28 08:19
/** * 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==true)                {                    pre->next=cur->next;//will change the structure of the list                    needDelete=false;                }                else                    pre=cur;//will not change the structure of the list            }            cur=cur->next;        }            if(needDelete)            pre->next=NULL;//will change the structure of the list                 return dummy->next;        }};

原创粉丝点击