Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->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 head;
16         ListNode* result=new ListNode(head->val);
17         ListNode* tmp=result;
18         int prv=head->val;
19         for(ListNode* p=head->next;p!=NULL;p=p->next)
20         {
21             int t=p->val;
22             if(t==prv)
23             {
24                 continue;
25             }
26             ListNode* item=new ListNode(t);
27             tmp->next=item;
28             tmp=item;
29             prv=t;
30         }
31         return result;
32     }
33 };
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