LeetCode-M-Remove Duplicates from Sorted List II

来源:互联网 发布:淘宝全网举报中心网址 编辑:程序博客网 时间:2024/05/21 10:39

题意

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

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

Subscribe to see which companies asked this question.

解法

实现

/** * 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 || head->next == NULL) return head;        ListNode* pre = head;        ListNode* cur = head->next;        ListNode* next = NULL;        while(cur != NULL){            if(pre->val != cur->val){                if(next == NULL){                    head = pre;                    next = pre;                }else{                    next->next = pre;                    next = pre;                }                pre = cur;                cur = cur->next;            }else{                while(cur != NULL && cur->val == pre->val) cur = cur->next;                if(cur == NULL && next == NULL) return NULL;                else if(cur == NULL && next != NULL){                    next->next = NULL;                    return head;                }else if(cur != NULL && next == NULL){                    pre = cur;                    cur = cur->next;                    if(cur == NULL) return pre;                }else{                    next->next = cur;                    pre = cur;                    cur = cur->next;                }            }        }        return head;    }};
0 0
原创粉丝点击