LeetCode 82. Remove Duplicates from Sorted List II
原题链接在这里:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
题目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
题解:
类似Remove Duplicates from Sorted List, 不同就是要完全去掉duplicate.
当cur.next.val == cur.next.next.val 时,就一直移动dup = cur.next.next直到cur.next.val != dup.val. 然后cur的next指向dup.
Time Complexity: O(n), n 是list长度.
Space: O(1).
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode deleteDuplicates(ListNode head) { 11 if(head == null || head.next == null){ 12 return head; 13 } 14 15 ListNode dummy = new ListNode(0); 16 dummy.next = head; 17 ListNode cur = dummy; 18 while(cur.next != null && cur.next.next != null){ 19 if(cur.next.val != cur.next.next.val){ 20 cur = cur.next; 21 }else{ 22 ListNode dup = cur.next.next; 23 while(dup != null && cur.next.val == dup.val){ 24 dup = dup.next; 25 } 26 cur.next = dup; 27 } 28 } 29 30 return dummy.next; 31 } 32 }
AC C++:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* deleteDuplicates(ListNode* head) { 14 if(!head || !head->next){ 15 return head; 16 } 17 18 ListNode* dummy = new ListNode(-1, head); 19 ListNode* it = dummy; 20 while(it->next && it->next->next){ 21 if(it->next->val != it->next->next->val){ 22 it = it->next; 23 }else{ 24 ListNode* dup = it->next->next; 25 while(dup && dup->val == it->next->next->val){ 26 dup = dup->next; 27 } 28 29 it->next = dup; 30 } 31 } 32 33 return dummy->next; 34 } 35 };