Leetcode 83. Remove Duplicates from Sorted List

xiaoxiao2021-02-28  9

原题:

Given a sorted linked list, delete all duplicates such that each element appear onlyonce.

For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3.

解决方法: 创建一个dummy节点以用于返回,每次都将节点加入到结果中,然后检查有没有重复的节点,如果有,则跳过这些重复的节点。 代码: ListNode* deleteDuplicates(ListNode* head) { if (!head ||!head->next) return head; ListNode dummy(INT_MIN), *prev = &dummy; while(head){ prev->next = head; prev = head; while (head){ bool same = head->next && head->val == head->next->val; head = head->next; if (!same) break; } prev->next = NULL; } return dummy.next; }
转载请注明原文地址: https://www.6miu.com/read-1900303.html

最新回复(0)