OJ lintcode 删除排序链表中的重复元素

给定一个排序链表,删除所有重复的元素每个元素只留下一个。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出 1->1->2->null,返回 1->2->null
给出 1->1->2->3->3->null,返回 1->2->3->null

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: head node
     */
    ListNode *deleteDuplicates(ListNode *head) {
        // write your code here
        if(head==NULL){
            return NULL;
        }
        if(head->next==NULL){
            return head;
        }
        ListNode * pre=head;
        ListNode * p=head->next;

        while(p!=NULL){
            if(p->val==pre->val){
                pre->next=p->next;
                p=pre->next;
            }
            else{
                pre=pre->next;
                p=p->next;
            }
        }
        return head;
    }
};

你可能感兴趣的:(OJ lintcode 删除排序链表中的重复元素)