Remove Duplicates from Sorted List II

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.

C++:
01 /**
02  * Definition for singly-linked list.
03  * struct ListNode {
04  *     int val;
05  *     ListNode *next;
06  *     ListNode(int x) : val(x), next(NULL) {}
07  * };
08  */
09 class Solution {
10 public:
11     ListNode *deleteDuplicates(ListNode *head) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if(head==NULL)
15             return NULL;
16         ListNode* result=NULL;
17         ListNode* tmp=NULL;
18         int prv=head->val1;
19         for(ListNode* p=head;p!=NULL;p=p->next)
20         {
21             int t=p->val;
22             if((t!=prv)&&((p->next==NULL)||(t!=p->next->val)))
23             {
24                 if(result==NULL)
25                 {
26                     result=tmp=new ListNode(t);
27                 }
28                 else
29                 {
30                     ListNode* item=new ListNode(t);
31                     tmp->next=item;
32                     tmp=item;
33                 }
34             }
35             prv=t;
36         }
37         return result;
38     }
39 };
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s