给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5 输出: 1->2->5
示例 2:
输入: 1->1->1->2->3 输出: 2->3
题目标签:Linked List
题目链接:LeetCode / LeetCode中国
Language | Runtime | Memory |
---|---|---|
cpp | 4 ms | 1.3 MB |
/**
* 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* g = new ListNode(0);
g->next = head;
ListNode* p = g;
ListNode* q = head->next;
while (q) {
if (q->val == p->next->val) {
q = q->next;
} else {
if (p->next->next != q) {
p->next = q;
} else {
p = p->next;
}
q = q->next;
}
}
if (p->next->next != q) {
p->next = q;
}
return g->next;
}
};