原题链接:Remove Duplicates from Sorted List
分析:因为链表已经是有序的,所以重复的值都会集中在一起,所以直接遍历,删除重复值就行。
题解:
/**
* 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) {
/*
Time Complexity:O(N)
Space Complexity:O(1)
*/
if(!head || !head->next)return head;
ListNode* res=head;
while(head->next){
if(head->val==head->next->val)head->next=head->next->next;
else head=head->next;
}
return res;
}
};