给定一个已排序的链表的头?
head
?,?删除所有重复的元素,使每个元素只出现一次?。返回?已排序的链表?。
?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
}
};
一次遍历,去重即可
时间复杂度: O(N) 空间复杂度:O(1)
?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head || !head->next) return head;
ListNode* pre = head;
for(auto it = head -> next ; it ; it = it -> next)
if(it->val == pre->val) pre->next = it->next;
else pre = it;
return head;
}
};