[Leetcode]#82 Remove Duplicates from Sorted List II

来源:互联网 发布:单片机软件工程师岗位 编辑:程序博客网 时间:2024/06/11 19:35

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.

//#82 Remove Duplicates from Sorted List II//8ms 100%/** * 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)     {        if(head == NULL) return head;        bool action(false);        int cmp(0);        while(head->next != NULL && head->next->val == head->val)        {            action = true;            cmp = head->val;            while(head != NULL && head->val == cmp && action == true)            {                head = head->next;            }               action = false;            if(head == NULL) return head;        }           ListNode *p(head);        while(p->next != NULL && p->next->next != NULL)        {            if(p->next->val == p->next->next->val)            {                action = true;                cmp = p->next->val;                //p->next = p->next->next;                while(p->next != NULL && p->next->val == cmp && action == true)                {                    p->next = p->next->next;                }                action = false;            }            else            {                p = p->next;            }        }        return head;        }};
0 0
原创粉丝点击