给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2 输出: 1->2
示例 2:
输入: 1->1->2->3->3 输出: 1->2->3
题目标签:Linked List
题目链接:LeetCode / LeetCode中国
Language | Runtime | Memory |
---|---|---|
cpp | 8 ms | 876.5 KB |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
static auto _ = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head || !head->next) { return head; }
ListNode* p = head;
ListNode* q = head->next;
while (q) {
if (p->val == q->val) {
q = q->next;
ListNode* tmp = p->next;
p->next = q;
delete tmp;
} else {
p = p->next;
q = q->next;
}
}
return head;
}
};