Remove Duplicates from Sorted List I
1 2 3 4 5 6 7 8 9 10 11 12 13
|
public ListNode (ListNode head) { if (head == null || head.next == null) return head; ListNode ptr = head; while (ptr != null && ptr.next != null) { if (ptr.val == ptr.next.val) { ptr.next = ptr.next.next; } else { ptr = ptr.next; } } return head; }
|
Remove Duplicates from Sorted List II
因为可能把head也给删掉了,所以需要使用一个dummy node。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
public ListNode (ListNode head) { if (head == null || head.next == null) return head; ListNode dummy = new ListNode(-1); dummy.next = head; head = dummy; while (head.next != null && head.next.next != null) { if (head.next.val == head.next.next.val) { int val = head.next.val; while (head.next != null && head.next.val == val) { head.next = head.next.next; } } else { head = head.next; } } return dummy.next; }
|
近期评论