[LeetCode][JavaScript]Remove Duplicates from Sorted List II
Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
从链表中移除出现一次以上的节点。
递归,每次就比较两个节点:当前的和下一个。
三种情况:
1.有一个不存在,返回当前节点;
2.值相同,循环直到找到下一个不同的节点,递归;
3.值不同,留下当前节点,后面的节点递归,拼接起来作为返回值。
1 /** 2 * Definition for singly-linked list. 3 * function ListNode(val) { 4 * this.val = val; 5 * this.next = null; 6 * } 7 */ 8 /** 9 * @param {ListNode} head 10 * @return {ListNode} 11 */ 12 var deleteDuplicates = function(head) { 13 if(!head || !head.next){ 14 return head; 15 } 16 17 if(head.val === head.next.val){ 18 var value = head.val; 19 while(head && head.val === value){ 20 head = head.next; 21 } 22 return deleteDuplicates(head); 23 }else{ 24 var h = head; 25 head = deleteDuplicates(head.next); 26 h.next = head; 27 return h; 28 } 29 };