LeeCode-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.

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* deleteDuplicates(struct ListNode* head) 
 9 {
10     if(head==NULL)
11         return NULL;
12         
13     if(head!=NULL&&head->next==NULL)
14         return head;
15 
16 
17     if(head->next->next==NULL)
18     {
19         if(head->val==head->next->val)
20         {
21             head->next==NULL;
22             return head->next;
23         }
24         
25         if(head->val!=head->next->val)
26         {
27             return head;
28         }
29     }
30 
31 
32      struct ListNode* p;
33      p=head;
34 
35      int count=0;
36      while(p!=NULL)
37      {
38          p=p->next;
39          count++;
40      }
41 
42 
43      int *array;
44      array=(int *)malloc(count*sizeof(int));
45 
46      p=head;
47      int i=0;
48      while(p!=NULL)
49      {
50          array[i]=p->val;
51          i++;
52          p=p->next;
53      }
54 
55      p=head;
56      for(i=0;i<count-1;i++)
57      {
58         if(array[i]!=array[i+1])
59         {
60             p->val=    array[i];
61             p=p->next;
62         }
63      }
64 
65      p->val=array[count-1];
66      p->next=NULL;
67 
68      return head;
69 }

 

posted @ 2015-07-20 09:18  vpoet  阅读(132)  评论(0编辑  收藏  举报