leetcode-142. 环形链表 II;83. 删除排序链表中的重复元素

62 阅读1分钟

142. 环形链表 II

方法一:快慢指针

Pasted image 20240703214839.png

var detectCycle = function(head) {
    if(head === null){
        return null;
    }
    let slow = head, fast = head;
    while(fast !== null){
        slow = slow.next;
        if(fast.next !== null){
            fast = fast.next.next;
        }else{
            return null;
        }
        if(slow === fast){
            let flag = head;
            while(flag !== slow){
                flag = flag.next;
                slow = slow.next;
            }
            return flag;
        }
    }
    return null;
};

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

注意点: 1、首先判断是否为空; 2、定义cur = head,改变cur的指向,head不能变!

var deleteDuplicates = function(head) {
    if (!head) {
        return head;
    }
    let cur = head
    while(cur.next){
        if(cur.val === cur.next.val){
            cur.next = cur.next.next;
        }else{
            cur = cur.next
        }
    }
    return head;
};