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.


Classical Two pointers method to Linked List.

 ListNode* deleteDuplicates(ListNode* head) {
        if(!head || !head->next) return head;
        ListNode* newHead = head;
        ListNode* slow = head;
        ListNode* fast = head->next;
        while(fast) {
            if(slow->val != fast->val) {
                slow->next = fast;
                slow = fast;
                fast = fast->next;
            } else {
                fast = fast->next;
            }
        }
        slow->next = NULL;
        return newHead;
    }

你可能感兴趣的:(LeetCode 83. Remove Duplicates from Sorted List)