1. 题目
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
class Solution {
public:ListNode* deleteDuplicates(ListNode* head) {if(!head || !head->next)//个数小于2return head;ListNode *cur = head, *nt = head->next;while(nt){if(cur->val == nt->val)nt = nt->next;//找到不一样的valelse{cur->next = nt;cur = nt;nt = nt->next;}}cur->next = NULL;//1-2-3-3-3,最后一次cur->next = NULLreturn head;}
};
我的CSDN博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!