LeetCode 82. Remove Duplicates from Sorted List II

来源:互联网 发布:新西兰留学利弊端 知乎 编辑:程序博客网 时间:2024/05/18 02:12

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.

answer:

class Solution {public:    ListNode* deleteDuplicates(ListNode* head) {        if(head == NULL) return head;        ListNode * start = head, * pre = head, * index = head;        int same = 0;        while(index != NULL){            if(index->val != start->val){                if(same > 1){                    if(start == head) head = index;                    else pre->next = index;                    same = 1;                    start = index;                }                else{                    same = 1;                    pre = start;                    start = index;                }            }            else same ++;            index = index->next;        }        if(start == head && head->next != NULL) head = NULL;        if(same > 1) pre->next = NULL;        return head;    }};



0 0
原创粉丝点击