LeetCode 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 .
一、アルゴリズム分析
先頭ノードでない単一チェーンテーブルを処理し、削除に関わる場合は削除の先頭ノードかどうかを考慮する必要がある.また、ヘッダノードが空の場合を考慮する必要がある.
二、C言語実現
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* deleteDuplicates(struct ListNode* head) {
    struct ListNode *pre,*p;
    if(head==NULL){
        return head;
    }
    while(head!=NULL && head->next!=NULL && head->next->val==head->val){
        head=head->next;
    }
    pre=head;
    p=head->next;
    while(p){
        if(p->val==pre->val){
            pre->next=p->next;
            p=p->next; 
        }else{
            pre=p;
            p=p->next;
        }
    }
    return head;
}