49 lines
1.4 KiB
JavaScript
49 lines
1.4 KiB
JavaScript
/**
|
||
* Definition for singly-linked list.
|
||
* function ListNode(val, next) {
|
||
* this.val = (val===undefined ? 0 : val)
|
||
* this.next = (next===undefined ? null : next)
|
||
* }
|
||
*/
|
||
/**
|
||
* @param {ListNode} head
|
||
* @return {ListNode}
|
||
*/
|
||
const deleteDuplicates = function (head) {
|
||
|
||
};
|
||
|
||
function ListNode(val, next) {
|
||
this.val = (val === undefined ? 0 : val);
|
||
this.next = (next === undefined ? null : next);
|
||
}
|
||
|
||
/*
|
||
思路:先建立哑节点,用于处理头部重复的情况,用cur来遍历整个链表,如果cur.next和cur.next.next 的值
|
||
相等,那么表示从cur.next开始发生了重复,我们记录这个val,从cur.next开始删除所有值等于val的节点;如果
|
||
cur.next和cur.next.next不相等,那么就没有重复,将cur移动到下一个节点cur = cur.next
|
||
*/
|
||
|
||
function f1(head) {
|
||
if (!head) {
|
||
return head;
|
||
}
|
||
const dummyHead = new ListNode(-1);
|
||
dummyHead.next = head;
|
||
let cur = dummyHead;
|
||
let curVal; // 保存重复节点的val
|
||
// 从哑节点开始,查看next和next.next是否相等
|
||
while (cur.next && cur.next.next) {
|
||
if (cur.next.val === cur.next.next.val) {
|
||
curVal = cur.next.val;
|
||
// 检测cur.next的值是否等于curVal,如果等于就删除这个节点
|
||
while (cur.next && cur.next.val === curVal) {
|
||
cur.next = cur.next.next;
|
||
}
|
||
} else {
|
||
cur = cur.next;
|
||
}
|
||
}
|
||
return dummyHead.next;
|
||
}
|