给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head || !head->next)//个数小于2
return head;
ListNode *cur = head, *nt = head->next;
while(nt)
{
if(cur->val == nt->val)
nt = nt->next;//找到不一样的val
else
{
cur->next = nt;
cur = nt;
nt = nt->next;
}
}
cur->next = NULL;//1-2-3-3-3,最后一次cur->next = NULL
return head;
}
};