给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
解答:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head==nullptr) return head;
// set<int> dictionary;
struct ListNode* ans;
ans = head;
// dictionary.emplace(head->val);
while(head->next){
if(head->val == head->next->val){
head->next = head->next->next;
}else{
// dictionary.emplace(head->next->val);
head = head->next;
}
}
return ans;
}
};
注意上面C++ 代码中并没有释放被删除的链表节点的空间。如果在面试中遇到本题,读者需要针对这一细节与面试官进行沟通