leetcode #82 in cpp

来源:互联网 发布:网络问卷调查技巧 编辑:程序博客网 时间:2024/06/05 18:13

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.

Solution: 

The solution is to use a pointer 'cur' pointing to a node. Then we find out if cur node has duplicates, by comparing its next val to its val. If its next is a duplicate, mark cur as 'should be deleted', and then delete its next. We use this method to delete all duplicates of cur node. After deleting all cur's duplicates,  if cur is marked as 'should be deleted', then we delete cur node. 

Example: [1,1,1,2,2,3,4,5,5, 6], shoudDelete = false; cur node is the first node. 

1. 1(cur)->1(next)->1->2->2->3->4->5->5->6, next is the same, delete next. Mark shouldDelete.

2. 1(cur)-> 1(next)-> 2->2->3->4->5->5->6. next is the same, delete next. 

3.1(cur)->2(next)->2->3->4->5->5->6. next is not the same. Up to now we delete all duplicates of 1. 

4. Since cur is marked as shouldDelete, 1 is delete. cur goes to 2. 

5. 2(cur)->2(next)->3->4->5->5->6. next is the same, mark shouldDelete. And delete next. 

6. 2(cur)->3(next)->4->5->5->6. Because of shouldDelete, 2 is deleted. 

7. 3(cur)->4(next)->5->5->6. 3 is not the same as next, move cur. 

8. 3->4(cur)->5(next)->5(next)->6. 4 is not the same as next, move cur. 

9.3->4->5(cur)->5(next)->6. 5 is the same as next. Mark shouldDelete and delete next.

10. 3->4->5(cur)->6(next). delete cur. 

11. 3->4->6(cur)->null. 

Done.

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 || !(head->next)) return head;                ListNode *cur = head;        ListNode *prev = head;        bool deleteCur = false;                while(cur){                        deleteCur = false;                        while(cur->next&&cur->next->val == cur->val){//if current node is duplicated, delete its duplicates after it                deleteCur = true;                cur->next = cur->next->next;            }                        if(deleteCur){//if current node is duplicated, we need to delete current node                if(cur==head){//if current node is the head, update the head                    head = head->next;                    prev = head;                    cur = head;                }else{//if current node is not the head, simply put its prev's next = current node's next, and update cur                    prev->next = cur->next;                    cur = prev->next;                }            }else{//if current node is not duplicated, move prev to current number, and move cur to next number                prev = cur;                cur = cur->next;            }                    }        return head;    }};


0 0
原创粉丝点击