Tag:List
Difficulty:Medium
Problem
给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
这道题与83.Remove Duplicates from Sorted ListII 不同的是这里要删除所有的重复项
Solution
首先,由于链表开头可能会重复,被删掉头指针会改变,所以这里定义一个新的节点,并且附上原链表。然后定义两个指针pre和cur分别指向前驱节点和当前。当pre指向新节点时,cur从下个位置往后遍历直到不同项。然后通过判断cur与pre.next确定cur是否重复。
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode res = new ListNode(-1), pre = res;
res.next = head;
while (pre.next != null) {
ListNode cur = pre.next;
while (cur.next != null && cur.next.val == cur.val) {
cur = cur.next;
}
if (cur != pre.next) {
// 中间有重复元素, cur舍去
pre.next = cur.next;
} else {
// 没有重复, pre后移
pre = pre.next;
}
}
return res.next;
}