题目:给定一个已排序的链表的头 head
, 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
思路:注意删除所有重复过的节点的思路
代码:
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(0, head);
ListNode cur = dummy;
while (cur.next != null && cur.next.next != null) {
int value = cur.next.val;
if (cur.next.next.val == value) {
while (cur.next != null && cur.next.val == value) {
cur.next = cur.next.next; // 把所有值=val的全部删除
}
} else
cur = cur.next;
}
return dummy.next;
}
}
性能:
时间复杂度o(n)
空间复杂度o(1)