Leetcode: Remove Duplicates from Sorted List II

来源:互联网 发布:网络视频服务器 租赁 编辑:程序博客网 时间:2024/05/17 03:39

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.

/** * 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)return NULL;ListNode* p = head;ListNode* pre = head->next;set<int> dupnum;while(pre){if(pre && pre->val == p->val)dupnum.insert(p->val);p=pre;pre=pre->next;}set<int>::iterator it;it = dupnum.find(head->val);if(it != dupnum.end()){pre = head;while(pre && dupnum.find(pre->val) != dupnum.end())pre=pre->next;if(pre==NULL)return NULL;p = head;head=pre;ListNode* tmp = p;while(p !=head){p=tmp->next;delete tmp;tmp=p;}}p=head;pre=p->next;while(pre){if(dupnum.find(pre->val) != dupnum.end()){p->next=pre->next;delete pre;pre=p->next;}else{p = pre;pre = pre->next;}}return head;    }};



原创粉丝点击