Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
public ListNode deleteDuplicates(ListNode head) {
if (head == null)
return head;
ListNode p1 = head;
while (p1.next != null) {
if (p1.val == p1.next.val) {
p1.next = p1.next.next;
} else {
p1 = p1.next;
}
}
return head;
}
比较简答,LeetCode官方链接
public ListNode deleteDuplicates(ListNode head) {
ListNode current = head;
while (current != null && current.next != null) {
if (current.next.val == current.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
这里就是把为空的判断放在了while循环里,看起来代码时简单了很多,但是我觉得这样子还不好,每次循环的时候都要去判断一下。