Shu-How Zの小窝

Loading...

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

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

class ListNode {
    constructor(val, next) {
        this.val = (val === undefined ? 0 : val)
        this.next = (next === undefined ? null : next)
    }
}
var deleteDuplicates = function(head) {
    let p=head
    //head have val next
    while(p&&p.next){
        if(p.val===p.next.val){
            p.next=p.next.next
        }else{
            p=p.next
        }
    }
    // p have next not val
    return head
};
let arr = [1,2,2,3,3]
let head=buildLinkedList(arr)
console.log(deleteDuplicates(head));

function buildLinkedList(arr) {
    let head = new ListNode(0);
    let p = head;
    for (let i = 0; i < arr.length; i++) {
        p.next = new ListNode(arr[i]);
        p = p.next;
    }
    return head.next;
}

posted @ 2025-01-10 21:11  KooTeam  阅读(21)  评论(0)    收藏  举报