[LeetCode] Remove Duplicates from Sorted List、Remove Duplicates from Sorted List II

来源:互联网 发布:淘宝评价有什么好处 编辑:程序博客网 时间:2024/06/05 06:06

Remove Duplicates from Sorted List:

Given a sorted linked list, delete all duplicates such that each element appear only once.

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

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */#define LN ListNodeclass Solution {public:    ListNode *deleteDuplicates(ListNode *head) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        const int INVALID =INT_MAX;    LN guard(INVALID);    guard.next=head;    LN* pre=&guard;    LN* cur=head;    while(cur)    {    if ( cur->val == pre->val )    {    pre->next=cur->next;    delete cur;    cur=pre->next;    }    else    {    pre=pre->next;    cur=cur->next;    }    }    return guard.next;    }};


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.

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

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */#define LN ListNodeclass Solution {public:    ListNode *deleteDuplicates(ListNode *head) {        // Start typing your C/C++ solution below        // DO NOT write int main() function                const int INVALID=INT_MAX;    LN guard(INVALID);    guard.next=head;        LN* pTail=&guard;    LN* cur=head;    while(cur)    {    if ( cur->next==NULL || cur->val!=cur->next->val)    {    pTail->next=cur;    pTail=pTail->next;    cur=cur->next;    }    else    {    int v=cur->val;    while(cur&&cur->val==v)    {    pTail->next=cur->next;    delete cur;    cur=pTail->next;    }    }    }    return guard.next;    }};


原创粉丝点击