【每日一题刷LeetCode】删除排序链表中的重复元素(C#)

  1. 删除排序链表中的重复元素

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

返回同样按升序排列的结果链表
在这里插入图片描述
提示:

链表中节点数目在范围 [0, 300] 内
-100 <= Node.val <= 100
题目数据保证链表已经按升序排列

首先都要判断一下链表是否为空
思路1:因为是有序的链表,所以只需要比对相邻的元素是否相同,双指针进行比较
p->指向不重复的最后一个节点
q->进行遍历
若p->==q->则q->=q.next->

思路2:直接在链表上操作,如果相邻两个相同直接把指针指向下一个,不占用额外空间

方法一
public ListNode DeleteDuplicates(ListNode head)
        {
            if (head == null || head.next == null)
            {
                return head;
            }

            ListNode currentNode = head;
            ListNode loopNode = head.next;

            while (loopNode != null)
            {
                if (loopNode.val != currentNode.val)
                {
                    currentNode.next = loopNode;
                    currentNode = loopNode;
                }

                loopNode = loopNode.next;
            }
            currentNode.next = null;

            return head;
        }

方法一

方法二
public class Solution {
    public ListNode DeleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
            {
                return head;
            }

        var rememberTop = head;
        var next = head.next;
        while(head != null && next != null)
        {
            if(next.val == head.val)
            {
                next = next.next;
                head.next = next;
            }
            else
            {
                head = head.next;
                next = head.next;
            }
        }

        return rememberTop;
    }
}

方法二

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值