【LeetCode】 82. Remove Duplicates from Sorted List II 删除排序链表中的重复元素 II(Medium)(JAVA)

【LeetCode】 82. Remove Duplicates from Sorted List II 删除排序链表中的重复元素 II(Medium)(JAVA)

题目地址: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

题目描述:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Return the linked list sorted as well.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

题目大意

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。

解题方法

1、查看后一个元素是否和当前元素相同,如果相同遍历到不相同为止
2、出现相同遍历结束后,继续判断下一个是否重复
3、需要每次设置 pre.next = null

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode res = new ListNode(0);
        ListNode pre = res;
        while (head != null) {
            int val = head.val;
            if (head.next != null && head.next.val == val) {
                while (head != null && head.val == val) {
                    head = head.next;
                }
                continue;
            }
            pre.next = head;
            pre = head;
            head = head.next;
            pre.next = null;
        }
        return res.next;
    }
}

执行用时 : 1 ms, 在所有 Java 提交中击败了 95.33% 的用户
内存消耗 : 39.5 MB, 在所有 Java 提交中击败了 5.22% 的用户

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值