48. Remove Duplicates from Sorted List && Remove Duplicates from Sorted List II

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.

思路: Easy. 依第二个开始,从前往后走一遍,若下一个相同,则删掉,迈过去,否则,走一步。

/**
 * 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 *p = head;
        while(p && p->next) {
            if(p->val == p->next->val) {
                ListNode *q = p->next;
                p->next = p->next->next;
                free(q);
            }
            else p = p->next;
        }
        return head;
    }
};

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

 或

/**
 * 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 pseudoHead(0);
        pseudoHead.next = head;
        ListNode *pre, *cur;
        pre = &pseudoHead;
        while(head) {
            for(cur = head->next; cur && cur->val == head->val; cur = cur->next);
            if(head->next != cur) {
                pre->next = cur;
                head = cur;
            }
            else { pre = head; head = head->next; }
        }
        return pseudoHead.next;
    }
};
原文地址:https://www.cnblogs.com/liyangguang1988/p/3954100.html