2015年7月2日星期四

LeetCode: Remove Duplicates from Sorted List

Simple two pointers problem:


/**
 * 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) {
        ListNode*  p, *q;
        if(head==NULL) return NULL;
        p=head;
        q=p->next;
        while(q){
            if(p->val == q->val){
                p->next=q->next;
                delete q;
                q=p->next;
                continue;
            }
            p=q;
            q=q->next;
        }
        return head;
    }
};

没有评论:

发表评论