题目
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
解析
由于已经是排序链表,直接判断next的值是不是等于当前节点的值
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* cur = head;
while (cur && cur->next) {
if (cur->val == cur->next->val) cur->next = cur->next->next;
else cur = cur->next;
}
return head;
}
};
如果链表是无序的,用unordered_set记录即可
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
// private:
// unordered_set<int> record;
public:
ListNode* deleteDuplicates(ListNode* head) {
// ListNode* h = head;
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* pre = dummy;
ListNode* cur = dummy->next;
while (cur) {
if (record.find(cur->val) == record.end()) {
record.insert(cur->val);
pre = pre->next;
cur = cur->next;
}
else {
pre->next = cur->next;
cur = cur->next;
}
}
return dummy->next;
}
};