Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
Given
1->1->2
, return 1->2
.Given
1->1->2->3->3
, return 1->2->3
.
-------------------------------------------------
This problem doesn't need a dummy in head, as the first one can be functioned as a dummy due to that the first node is always kept in the process.
//////////////////////////////////////////////
//code
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
//check
input
if (head == NULL)return head;
ListNode *tmp = head, *p = head;
while (p->next != NULL){
if (p->next->val ==
p->val){
tmp = p->next;
p->next =
tmp->next;
delete tmp;
}
else p = p->next;
}
return head;
}
};
No comments:
Post a Comment