3月3日(4) Remove Duplicates from Sorted List

原题 Remove Duplicates from Sorted List

有序单链表去重,delete 只能对指针起作用。

/**
 * 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 == NULL) return NULL;

        ListNode *pp = head;
        ListNode *p = head->next;
        
        while (p != NULL)
        {
            if (p->val == pp->val)
            {
                pp->next = p->next;
                delete p;
                p = pp->next;
                continue;
            }
            pp = p;
            p = p->next;
        };
        return head;
    }
};
posted @ 2014-03-03 19:32  miuc  阅读(145)  评论(0编辑  收藏  举报