LeetCode-83. 删除排序链表中的重复元素(JavaScript)

245 阅读1分钟

题目链接:leetcode-cn.com/problems/re…

https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/05e9eaa5b74e45f892a8f485037bbb31~tplv-k3u1fbpfcp-zoom-1.image

解法:

还是快慢指针的办法

跟数组一样,只是变成了链表的操作方法

快指针遍历链表,遇到与慢指针不相等的,让慢指针的 next 指向快指针,中间重复的就不要了

在遍历完成后,慢指针的 next 要指向 null,因为后面的可能是 null 或者重复值

/*
 * @lc app=leetcode.cn id=83 lang=javascript
 *
 * [83] 删除排序链表中的重复元素
 */

// @lc code=start
/**
 * 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}
 */
var deleteDuplicates = function (head) {
    if (head === null || head.next === null) return head
    let slow = head
    let fast = head
    while (fast !== null) {
        // 当快指针遇到与慢指针不相等的值时,慢指针的 next 指向快指针,略过中间的重复值(不管有没有)
        if (fast.val !== slow.val) {
            slow.next = fast
            // 慢指针往前走一步
            slow = slow.next
        }
        fast = fast.next
    }
    // 将慢指针后面的值置空,可能为空,可能是重复值
    slow.next = null
    return head
};
// @lc code=end