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         if(head == NULL || head->next == NULL)
 5             return head; 
 6         ListNode *p;
 7         ListNode *q;
 8         q=head;
 9         p=head->next; 
10         while(p!=NULL)
11         {
12             if(p->val==q->val)
13             {
14                 q->next=p->next;
15                 p=q->next;
16             }else{
17                    p=p->next;
18                 q=q->next;
19             }    
20         }    
21         return head;  
22     }
23 };

 

posted on 2015-04-19 18:57  黄瓜小肥皂  阅读(124)  评论(0编辑  收藏  举报