Remove Duplicates from Sorted List

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        if(head)
        {
            ListNode *p,*q;
            p=head;
            if(p->next)
            {
                q=p->next;
            }
            while(p->next)
            {
                if(p->val==q->val)
                {
                    p->next=q->next;
                    free(q);
                    q=p->next;
                }
                else
                {
                    p=q;
                    q=p->next;
                }
            }
        }
        return head;
    }
};

代码写的好看一些

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *deleteDuplicates(ListNode *head) {
12         if(head)
13         {
14             ListNode *p,*q;
15             p=head;
16             while(p->next)
17             {
18                 q=p->next;
19                 if(p->val==q->val)
20                 {
21                     p->next=q->next;
22                     free(q);
23                 }
24                 else
25                 {
26                     p=q;
27                 }
28             }
29         }
30         return head;
31     }
32 };

 

posted on 2014-03-06 21:21  crane_practice  阅读(112)  评论(0编辑  收藏  举报

导航