Remove Duplicate

Leetcode #83


Description:

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

Example:

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

Idea:

use curr, next pointer

第二题是“Leetcode 82. Remove Duplicates from Sorted List II”, duplicate全部删除。

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

Code:

/**
 * 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 *curr, *next;
        curr=head;
        next=head->next;
        while(next!=NULL){
            if(curr->val==next->val){
                curr->next = next->next;
            }
            else{
                curr=curr->next;
            }
            next=next->next;
        }
        return head;
    }
};

第二题

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head==NULL || head->next==NULL)
            return head;

        ListNode *prev, *curr, *next;
        ListNode dummy(-1);
        bool hasDuplicate=false;
        prev=&dummy;
        prev->next=head;
        curr=head;
        next=head->next;
        while(next!=NULL){
            if(curr->val==next->val){
                hasDuplicate=true;
                curr->next = next->next;
            }
            else{
                if(hasDuplicate){
                    prev->next=curr->next;
                    hasDuplicate=false;
                }
                else{
                    prev=prev->next;
                }
                curr=curr->next;
            }
            next=next->next;
        }
        if(hasDuplicate)
            prev->next=curr->next;
        return dummy.next;
    }
};

results matching ""

    No results matching ""