LeetCode 83. 删除排序链表中的重复元素

mac2022-06-30  30

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。 示例 1: 输入: 1->1->2 输出: 1->2 示例 2: 输入: 1->1->2->3->3 输出: 1->2->3 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解:类似于数组去重,利用快慢指针实现

ListNode* deleteDuplicates(ListNode* head) { if (head == NULL) return NULL; ListNode *slow = head, *fast = head->next; while (fast != NULL) { if (slow ->val != fast->val) { slow = slow->next; slow ->val = fast->val; } else fast = fast->next; } slow->next = NULL; return head; }
最新回复(0)