algorighm/top-interview-leetcode150/link/82删除排序列表中的重复元素.js

49 lines
1.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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;
}