Remove Duplicates from Sorted List II

image.png

要注意的问题:因为可能head也需要被删掉,所以需要一个dummy节点。

/**
 * 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 *dummy = new ListNode(0);
        ListNode *cur = head;
        ListNode *prev = dummy;
        int flag = 0;
        while(cur){
            if(cur->next && cur->val == cur->next->val){
                cur->next = cur->next->next;
                flag = 1;
            }
            if(flag){
                prev->next = cur->next;
                cur = prev->next;
                flag = 0;
                cout<val<next;
            }
        }
        return dummy->next;
    }
};

你可能感兴趣的:(Remove Duplicates from Sorted List II)