当前位置: 首页 > 图灵资讯 > 技术篇> #yyds干货盘点# LeetCode面试题:删除排序链表中的重复元素 II

#yyds干货盘点# LeetCode面试题:删除排序链表中的重复元素 II

来源:图灵教育
时间:2023-04-21 10:04:11

1.简述:

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

示例 1:

输入:head = [1,2,3,3,4,5]

输出:[1,2,5]

示例 2:

输入:head = [1,1,1,2,3]

输出:[2,3]

2.实现代码:

class Solution {    public ListNode deleteDuplicates(ListNode head) {        if (head == null) {            return head;        }                ListNode dummy = new ListNode(0, head);        ListNode cur = dummy;        while (cur.next != null && cur.next.next != null) {            if (cur.next.val == cur.next.next.val) {                int x = cur.next.val;                while (cur.next != null && cur.next.val == x) {                    cur.next = cur.next.next;                }            } else {                cur = cur.next;            }        }        return dummy.next;    }}