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.

有序链表去重,两个指针,一次遍历,一个指针tail1指向原链表尾部,一个指针tail2指向去重后的链表尾部,如果tail1valtail2val不一样,则说名这个没出现过,就把这个tail1val移动到tail2的下一个节点的val上。

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

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