LeetCode-82-Remove Duplicates from Sorted List II

算法描述:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

解题思路:列表题,画出图基本上就能解出来。

    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* dummy = new ListNode(-1);
        dummy->next =head;
        ListNode* cur = dummy;
        while(cur->next!=nullptr && cur->next->next!=nullptr){
            if(cur->next->val == cur->next->next->val){
                int data = cur->next->val;
                while(cur->next!=nullptr && cur->next->val == data){
                    cur->next = cur->next->next;
                }
            }else{
                cur = cur->next;
            }
        }
        return dummy->next;
    }

 

posted on 2019-02-01 12:48  无名路人甲  阅读(84)  评论(0编辑  收藏  举报