Description:
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
.
My code:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
if(!head) {
return null;
}
let singleArr = [], singleListNode = head; // 數(shù)組用于判斷元素是否出現(xiàn)過
let curListNode = head;
while(head != null) {
if(singleArr.indexOf(head.val) == -1) {
singleArr.push(head.val);
head = head.next;
} else {
while(curListNode.next != null) { // 找出重復(fù)元素的第一個(gè)節(jié)點(diǎn)棠涮,刪除它的下一個(gè)節(jié)點(diǎn)
if(curListNode.val == head.val) {
break;
} else {
curListNode = curListNode.next;
}
}
curListNode.next = head.next;
head = head.next;
}
}
return singleListNode;
};