本文最后更新于:2021年1月21日 下午
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
示例 2:
| 输入: 1->1->2->3->3 输出: 1->2->3
|
Solution
参考:《算法小抄》5.5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if not head: return slow, fast = head, head.next while fast: if fast.val != slow.val: slow.next = fast slow = slow.next fast = fast.next slow.next = None return head
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
class Solution { public: ListNode* deleteDuplicates(ListNode* head) {
ListNode* cur = head; while(cur != NULL && cur->next != NULL){ if(cur->val == cur->next->val){ ListNode* delNode = cur->next; cur->next = delNode->next; delete delNode; } else cur = cur->next; } return head; } };
|