删除给出链表中的重复元素(链表中元素从小到大有序),使链表中的所有元素都只出现一次
例如:
给出的链表为
,返回
.
给出的链表为
,返回
.
例如:
给出的链表为
给出的链表为
数据范围:链表长度满足
,链表中任意节点的值满足
进阶:空间复杂度
,时间复杂度 )
function ListNode(x) {
this.val = x;
this.next = null;
}
/**
*
* @param head ListNode类
* @return ListNode类
*/
function deleteDuplicates(head) {
// write code here
//如果head为空,直接返回
if (!head) {
return head;
}
let cur = head,
next = head.next;
while (next) {
//如果当前节点的值和下一个节点的值相等,next走,cur不动
if (cur.val === next.val) {
cur.next = next.next;
next = next.next;
}
//否则,cur移到next,next移到next的下一个
else {
cur = next;
next = next.next;
}
}
return head;
}
module.exports = {
deleteDuplicates: deleteDuplicates
};