83. Remove Duplicates from Sorted List

题目:

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

 

Example 1:

Input: head = [1,1,2]
Output: [1,2]

Example 2:

Input: head = [1,1,2,3,3]
Output: [1,2,3]

 

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

 

 

思路:

刚做了这个的二,顺带把这个一也做了,这题不用把重复的数字完全删除,而是保留所有出现过的数字一次即可。思路就是简单的loop,如果下一个为空了,那么当前这个肯定是unique的,直接break即可;否则如果当前和下一个相等,那么就跳过下一个,这里注意跳过以后,不用当前节点不用往下移,因为我们下一轮循环还要再次判断当前节点和现在的下一个节点(即原本的下下个节点)是否一致,这里举例[1, 1, 1],如果我们第一轮跳过了中间的1,list变成了1->1,那么当前节点往下,直接就是后面那个1然后跳出循环了,这种情况依然有重复数字;如果不相同,则说明当前节点是unique的,往下走一格即可。

 

 

 

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head||!head->next)
            return head;
        ListNode* temp=head;
        while(temp)
        {
            if(!temp->next)
                break;
            if(temp->next->val==temp->val)
                temp->next=temp->next->next;
            else
                temp=temp->next;      
        }
        return head;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值