LeetCode 83. 删除排序链表中的重复元素
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1.创建一个指针idnex
2.比较index->val与index->next->val是否相等;
3.如果相同,index->next=index->next->next。
4 重复2-3过程。
5.如果不相同,index=index->next;
遍历完链表返回head;
/**
* 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) {
if(head==NULL)return head;
ListNode* index=head;
while(index->next!=NULL)
{
if(index->val==index->next->val)
{
index->next=index->next->next;
}
else
{
index=index->next;
}
}
return head;
}
};

时间复杂度O(n)
空间复杂度O(1)
本文详细解析了LeetCode83题目的解决方案,通过一次遍历链表,利用指针技巧,删除所有重复元素,确保每个元素只出现一次。提供C++实现代码,展示了如何在O(n)时间复杂度和O(1)空间复杂度下完成任务。
817

被折叠的 条评论
为什么被折叠?



