代码随想录 | Day04 | 链表Part02 | 24. 两两交换链表中的节点 |19.删除链表的倒数第N| 链表相交 | 142.环形链表II

64 阅读1分钟

24. 两两交换链表中的节点

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

image.png

var swapPairs = function(head) {
    let dummyHead = new ListNode(0,head)
    let cur = dummyHead
    while(cur.next!= null && cur.next.next !=null){
        let temp = cur.next
        let temp2 = cur.next.next.next  // 此时可以指向空值

        cur.next = cur.next.next
        cur.next.next = temp
        temp.next = temp2

        cur = cur.next.next
    }
    
    return dummyHead.next
};

19.删除链表的倒数第N个节点

思路 快慢指针找到倒数的位置

function(head, n) {
    let ret = new ListNode(0, head),
        slow = fast = ret;
    while(n--) fast = fast.next;
    while (fast.next !== null) {
        fast = fast.next; 
        slow = slow.next
    };
    slow.next = slow.next.next;
    return ret.next;
};

链表相交

var getIntersectionNode = function(headA, headB) {
    if(headA==null || headB==null) return null
    const lenA = getLength(headA)
    const lenB = getLength(headB)
    let dis = Math.abs(lenA-lenB)
    while(dis--){
        if(lenA>lenB){
            headA = headA.next
        }else{
            headB = headB.next
        }
    }

    while(headA!=null){
        if(headA== headB){
            return headA
        }
        headA = headA.next
        headB = headB.next
    }
    return null
};

function getLength(head){
    let temp = head
    let length = 1
    while(temp.next!=null){
        length +=1
        temp = temp.next
    }

    return length
}

142.环形链表II

思路、 快慢指针判断有无环,相遇时,慢指针从头触发遇到的第一个位置就是快指针

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