43. 删除链表中的重复节点

1. 题目

存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次

返回同样按升序排列的结果链表。

image-20210528154840914

2. 分析

  1. 递归:
    1. 找终止条件:当head指向链表只剩一个元素的时候,自然是不可能重复的,因此return;
    2. 想想应该返回什么值:应该返回的自然是已经去重的链表的头节点;
    3. 每一步要做什么:宏观上考虑,此时head.next已经指向一个去重的链表了,而根据第二步,我应该返回一个去重的链表的头节点。因此这一步应该做的是判断当前的head和head.next是否相等,如果相等则说明重了,返回head.next,否则返回head
  2. 迭代:若当前节点值与下一节点值相同,则cur -> next = cur -> next -> next; 若不相同,则cur = cur -> next;

代码如下:

    // 递归
	ListNode* deleteDuplicates(ListNode* head) {
        if(head == nullptr || head -> next == nullptr)
            return head;
        head -> next = deleteDuplicates(head -> next);
        if(head -> next -> val == head -> val)    head = head -> next;
        return head;
    }

	// 迭代
	ListNode* deleteDuplicates(ListNode* head) {
        if(!head) return nullptr;
        ListNode* cur = head;
        while(cur -> next){
            if(cur -> val == cur -> next -> val)
                cur -> next = cur -> next -> next;
            else
                cur = cur -> next;
        }
        return head;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值