【力扣 007】 83. 删除排序链表中的重复元素

83. 删除排序链表中的重复元素

解法1:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) 
    {
        if(!head) return head;
        ListNode *dumy = new ListNode(-1), *pre = dumy;
        dumy->next = head;
        ListNode *p = head;

        while(p)
        {
            while(p->next && p->val == p->next->val)
                p = p->next;
            
            if(pre->next == p)
            {
                pre = p;
                p = p->next;
            }
            else
            {
                pre->next = p;
                pre = pre->next;
                p = p->next;
            }
        }
        return dumy->next;
    }
};

 

  

  

posted @ 2019-03-29 11:38  苏格拉底的落泪  阅读(125)  评论(0编辑  收藏  举报