https://leetcode.com/problems/remove-duplicates-from-sorted-list/
Input: 1->1->2
Output: 1->2
public ListNode deleteDuplicates(ListNode head) {
ListNode res = head;
while (head != null && head.next != null) {
if (head.val == head.next.val) {
head.next = head.next.next;
continue;
}
head = head.next;
}
return res;
}
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
Input: 1->2->3->3->4->4->5
Output: 1->2->5
if (head == null || head.next == null) {
return head;
}
ListNode res = new ListNode(-1);
ListNode 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) {
pre.next = cur.next;
} else {
pre = pre.next;
}
}
return res.next;
网友评论