描述:
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 2->3
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii
代码实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dum = new ListNode(-1);
ListNode p = dum;
ListNode pre = head, cur = head.next;
if (cur.val != pre.val) {
p.next = pre;
p = p.next;
}
while (cur != null) {
if (cur.val == pre.val || (cur.next != null && cur.val == cur.next.val)) {
while (cur.next != null && (pre.val == cur.val || cur.val == cur.next.val)) {
pre = pre.next;
cur = cur.next;
}
if (pre.val != cur.val) {
p.next = cur;
p = p.next;
}
} else {
p.next = cur;
p = p.next;
}
pre = pre.next;
cur = cur.next;
}
p.next = null;
return dum.next;
}
}