给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 2->3
代码如下:
public class MyLeetCode82 { public static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public static ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } ListNode fakeNode = new ListNode(-1); ListNode root = fakeNode; ListNode prev = head; ListNode cur = head; while (cur != null && cur.next != null) { while (cur.next != null && cur.next.val == prev.val) { cur = cur.next; } if (cur == prev) { // 指针没动过,代表当前第一个就是不重复的 root.next = prev; root = root.next; } prev = cur.next; cur = cur.next; } if (prev == cur && prev != null) { root.next = cur; root = root.next; } root.next = null; return fakeNode.next; } }