首页 > 代码库 > LeetCode:Remove Duplicates from Sorted List

LeetCode: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 class Solution{ 2 public: 3     ListNode *deleteDuplicates(ListNode *head){ 4         ListNode *p,*q; 5         if(head==NULL) 6         { 7             return head; 8         } 9         p=head;10         q=p->next;11         while(q!=NULL)12         {13             if(p->val==q->val)14             {15                 p->next=q->next;16                 free(q);17             }18             else19             {20                 p=q;21             }22             q=p->next;23         }24         return head;25     }26 };