给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

示例 1:
请添加图片描述

输入:head = [1,1,2]
输出:[1,2]
示例 2:
请添加图片描述

输入:head = [1,1,2,3,3]
输出:[1,2,3]

/**
 * 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) {
        return head
    }
    var cur = head
    while (cur.next) {
        if (cur.val == cur.next.val) {
            cur.next = cur.next.next
        } else {
            cur = cur.next
        }
    }
    return head
};

leetcode:https://leetcode.cn/problems/remove-duplicates-from-sorted-list/

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐