Douc1998 / My_Leetcode

Leetcode_题解
0 stars 0 forks source link

LeetCode 83. 删除排序链表中的重复元素 #131

Open Douc1998 opened 1 year ago

Douc1998 commented 1 year ago

题目

给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。

示例

image

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

image

输入: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 === null) return null;
    let prev = head, cur = head.next;
    while(cur){
        // 如果 prev.val 不等于 cur.val,则 prev 连接 cur,并且移动 prev 和 cur
        // 如果相等,则 cur 移动到下一个
        if(prev.val !== cur.val){
            prev.next = cur;
            prev = cur;
        }
        cur = cur.next;
    }
    // 最后一个 prev 的 next 要变为 null
    prev.next = null;
    return head;
};