For example,
Given
1->1->2
, return 1->2
.Given
1->1->2->3->3
, return 1->2->3
.跟array操作一样,O(n)的时间复杂度
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
//sanity check
if (head == NULL || head->next == NULL) return head;
ListNode* slow = head;
ListNode* fast = head;
while (fast != NULL) {
if (fast->val != slow->val) {
slow = slow->next;
slow->val = fast->val;
}
fast = fast->next;
}
slow->next = NULL;
return head;
}
};
No comments:
Post a Comment