LeetCode-083. Remove Duplicates from Sorted List

1. 题目

Remove Duplicates from Sorted List

对有序链表去重,使每个元素只出现1次

2. 分析

若链表长度小于2,直接结束
否则,遍历链表,当相邻元素相等时,删除后出现的重复元素

3. 代码

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return head;

        ListNode *start = head;
        while(start != NULL)
        {
            ListNode *cur = start;
            while(cur->next != NULL && cur->next->val == cur->val)
                cur = cur->next;

            start->next = cur->next;
            start = start->next;
        }

        return head;
    }
};

完整源代码放于github
相关代码:
LeetCode-082. Remove Duplicates from Sorted List II

猜你喜欢

转载自blog.csdn.net/tao_ba/article/details/80656789