Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
思路:
同第82题,但是只需要当检测到重复的数后删除后面的数。代码如下:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode feakHead(0);
feakHead.next = head; head = &feakHead;
ListNode *curr = head;
while (curr->next){
if (curr->next->next && curr->next->val == curr->next->next->val){
curr->next = curr->next->next;
}
else curr = curr->next;
}
return head->next;
}
};