论坛首页 编程语言技术论坛

[Leetcode] Remove Duplicates from Sorted List 1 & 2

浏览 1428 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-10-03  

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;
        }
    }
};

 

/**
 * 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;
        }
    }
};

 

 

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.

 

 

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics