题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
public ListNode deleteDuplicates (ListNode head) { // write code here if(head == null) return null; ListNode cur = head; while(cur!=null&&cur.next!=null){ if(cur.val == cur.next.val){ cur.next = cur.next.next; } else cur = cur.next; } return head; }
//第一次出错 非法越界
没有考虑 元素已经为null的情况下没法 调用next 因此在while()中应该先判断自己是否已经为null
//第二次出错 三个相同的元素判断错误
这种去掉相同数字的链表题中应该确保下一个元素和本身不同的时候再指向下一个元素,不然只能将两个相同的元素变成一个不能将两个以上相同的元素变成一个。