Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5 Output: 1->2->5
Example 2:
Input: 1->1->1->2->3 Output: 2->3
Solution:
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Author: Huahua class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if (!head) return nullptr; ListNode dummy = ListNode(0); ListNode *p = &dummy; while (head) { int c = 0; while (head->next && head->next->val == head->val) { head = head->next; c++; } if (c == 0) p = p->next = head; else p->next = nullptr; head = head->next; } return dummy.next; } }; |
Related Problems
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment