[LeetCode] Remove Duplicates from Sorted List II

来源:互联网 发布:ubuntu 12.04 配置dns 编辑:程序博客网 时间:2024/06/08 16:48

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.

这道题和Remove Duplicates from Sorted List
区别在于,这道题是重复的元素都不保留。前面的题是重复的只保留一个。

我们的思路是有三个结点a,b,c,a表示的是已经删除过重复结点的链表尾节点,b表示当前节点,c表示b->next。当b和a的值不同时且和c的值不同时,才将b添加到新的链表中。循环推出的条件是c==NULL,此时如果b和a不同,则把curr->next变成b,相同的话则curr->next =NULL。

/** * 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* new_head = new ListNode(INT_MAX);        ListNode *a,*b,*c;        ListNode *curr;        a = new_head;        b = head;        c = head->next;        curr = new_head;        while(1){            if(c==NULL){                if(b->val!=a->val)                    curr->next = b;                else                    curr->next = NULL;                break;            }            else{                if(b->val!=a->val&&b->val!=c->val){                    curr->next = b;                    curr=b;                }                a = b;                b = c;                c = c->next;            }        }        return new_head->next;    }};

8ms AC

还有一种思路,技巧性更强一些
pre是已经移除了重复元素的链表的最后一个结点,初始为helper,当前的节点为curr。所以如果helper->next->val与curr->next->val相等则curr一直移动。当停止时如果helper->next==curr,则说明curr并没有移动,则加入curr这个节点,再移动helper和curr,helper = helper->next;(即helper=curr),curr = curr->next; 如果curr移动了,则此时helper->next应该指向curr->next,curr同样移动。

/** * 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 head;    ListNode* helper = new ListNode(0);    helper->next = head;    ListNode* pre = helper;    ListNode* cur = head;    while(cur!=NULL)    {        while(cur->next!=NULL && pre->next->val==cur->next->val)        {            cur = cur->next;        }        if(pre->next==cur)        {            pre = pre->next;        }        else        {            pre->next = cur->next;        }        cur = cur->next;    }    return helper->next;}};

8ms AC

0 0