[leetcode]82. Remove Duplicates from Sorted List II

来源:互联网 发布:淘宝自动发货系统 编辑:程序博客网 时间:2024/06/06 17:04

题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/#/description

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.


class Solution {public:    ListNode* deleteDuplicates(ListNode* head) {        if(!head||!head->next)            return head;        ListNode* newhead=new ListNode(-1);        newhead->next=head;        ListNode* t=newhead;        while(t->next)        {            if(t->next && t->next->next && t->next->val==t->next->next->val)            {                while(t->next && t->next->next && t->next->val==t->next->next->val)                {                    ListNode* temp=t->next->next;                    t->next->next=t->next->next->next;                    delete temp;                }                ListNode* temp=t->next;                t->next=t->next->next;                delete temp;            }            else if(t->next && t->next->next)            {                t=t->next;            }            else if(t->next && !t->next->next)            {                break;            }        }        return newhead->next;    }};


原创粉丝点击