`
cozilla
  • 浏览: 92067 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

[Leetcode] Remove Duplicates from Sorted List 1 & 2

 
阅读更多

Remove Duplicates from Sorted List

 
AC Rate: 984/2755
My Submissions

 

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) {}
 * };
 */
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        ListNode myhead(99), *prev, *s, *e;
        int cnt;
        prev = &myhead;
        myhead.next = head;
        s = head;
        while (s != NULL) {
            e = s->next;
            cnt = 0;
            while (e != NULL && e->val == s->val) e = e->next, cnt++;
            if (cnt == 0) {
                prev = s;
                s = e;
            }
            else {
                prev = s;
                del(s->next, e);
                s->next = e;
                s = e;
            }
        }
        return myhead.next;
    }
    
    void del(ListNode* s, ListNode* e) {
        // delete [s, e);
        ListNode *t;
        while (s != e) {
            t = s;
            s = s->next;
            delete t;
        }
    }
};

 

 

Remove Duplicates from Sorted List II

 
AC Rate: 567/2394
My Submissions

 

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) {}
 * };
 */
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        ListNode myhead(99);
        myhead.next = head;
        ListNode *prev = &myhead, *cur = head, *next;
        int cnt;
        while (cur != NULL) {
            next = cur->next;
            cnt = 0;
            while (next != NULL && next->val == cur->val) next=next->next, cnt++;
            if (cnt == 0) {
                prev = cur;
                cur = next;
            }
            else {
                prev->next = next;
                del(cur, next);
                cur = next;
            }
        }
        return myhead.next;
    }
    
    void del(ListNode* s, ListNode* e) {
        // delete [s, e);
        ListNode *t;
        while (s != e) {
            t = s;
            s = s->next;
            delete t;
        }
    }
};

 

 

 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics