83. 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) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == NULL || head->next == NULL) {
            return head;
        }

        ListNode *prev = head;
        while(prev->next){
            if(prev->val == prev->next->val){
                ListNode *temp = prev->next;
                prev->next = prev->next->next;
                delete temp;
            }else{
                prev = prev->next;
            }
        }
        return head;
    }
};

82. 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) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode **pHead = &head;

        if(head == NULL || head->next == NULL){
            return head;
        }

        while(*pHead){
            if((*pHead)->next && (*pHead)->val == (*pHead)->next->val){
                ListNode *temp = *pHead;
                while(temp && temp->val == (*pHead)->val)
                    temp = temp->next;
                *pHead = temp;
            }else
                pHead = &((*pHead)->next);
        }
        return head;
    }
};

递归的方法,不知道为什么比上面的快

/**
 * 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 NULL;
        if(head->next == NULL)  return head;

        int val = head->val;
        ListNode *p = head->next;

        if(val != p->val){
            head->next = deleteDuplicates(p);
            return head;
        }else{
          //此处注意对p非空的判断
            while(p && p->val == val)   p = p->next;
            return deleteDuplicates(p);
        }
    }
};

results matching ""

    No results matching ""