【链表】Leetcode 82. 删除排序链表中的重复元素 II【中等】

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

  • 给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。

示例 1:

在这里插入图片描述
输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]

解题思路

由于链表是已排序的,所以重复的节点会相邻出现。可以使用双指针法来解决这个问题,一个指针用于遍历链表,另一个指针用于跟踪上一个未重复的节点。

  • 遍历链表:使用两个指针pre和current。pre用于指向上一个未重复的节点,current用于遍历链表。
  • 删除重复节点:如果current和current.next的值相等,则继续向前遍历直到遇到不同的值为止。将pre.next指向当前遇到的第一个不同值节点。
  • 移动指针:如果current和current.next的值不同,pre移动到current位置,current继续向前遍历。
  • 返回结果:返回哨兵节点的下一个节点。

Java实现

public class DeleteDuplicates {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    public ListNode deleteDuplicates(ListNode head) {
        // 创建哨兵节点
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode current = head;
        
        while (current != null) {
            // 跳过当前节点后面所有的重复节点
            while (current.next != null && current.val == current.next.val) {
                current = current.next;
            }
            // 如果pre的下一个节点是current,说明当前节点没有重复
            if (pre.next == current) {
                pre = pre.next;
            } else {
                // 如果pre的下一个节点不是current,说明有重复节点,跳过所有重复节点
                pre.next = current.next;
            }
            current = current.next;
        }
        
        return dummy.next;
    }

    public static void main(String[] args) {
        DeleteDuplicates deleteDuplicates = new DeleteDuplicates();

        // 创建示例链表 1->2->3->3->4->4->5
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(4);
        head.next.next.next.next.next = new ListNode(4);
        head.next.next.next.next.next.next = new ListNode(5);

        // 删除重复节点
        ListNode newHead = deleteDuplicates.deleteDuplicates(head);
        printList(newHead); // 输出: 1->2->5
    }

    // 辅助方法:打印链表
    public static void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val);
            if (current.next != null) {
                System.out.print("->");
            }
            current = current.next;
        }
        System.out.println();
    }
}

时间空间复杂度

  • 时间复杂度:O(n),其中 n 是链表的节点数。需遍历链表一次。
  • 空间复杂度:O(1),只使用了几个额外的指针。
  • 14
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值