2015年8月10日 星期一

LEET code--Remove Duplicates from Sorted List

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.


current 只有再future不一樣的時候才會前進
future會每次循環都向前

這樣是避免連續出現同樣數字,保留current的  讓future去找誰重複
如果沒有重複就current向前





 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
struct ListNode* deleteDuplicates(struct ListNode* head) {
    if(head==NULL)return head;
    struct ListNode *current=head;
    struct ListNode *future=head->next;
    while(current!=NULL && future!=NULL){
        if(current->val == future->val){
            current->next=future->next;
            free(future);
            future=(current !=NULL) ? current->next: NULL;
        }
        else{
            current=current->next;
            future=(current !=NULL) ? current->next: NULL;
        }
    }
    return head;
}

沒有留言:

張貼留言