代码随想录算法训练营第4天 | 24. 两两交换链表中的节点 19. 删除链表的倒数第 N 个结点 面试题 02.07. 链表相交 142.环形链表II

40 阅读1分钟

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

注意点

1.终止条件 cur.next != null && cur.next.next != null

2.操作cur后两个节点

3.操作完成后,链表更改 cur = temp;

/**
 * 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 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 temp1 = temp.next.next;
        cur.next = temp.next;
        temp.next.next = temp;
        temp.next = temp1;
        cur = temp;
    }
    return dummyHead.next;


};

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

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function(head, n) {
    let dummyHead = new ListNode(0,head);
    let slow = dummyHead, fast = dummyHead;

    // fast先移动n步
    while (n && fast != null) {
        fast = fast.next;
        n--;
    }

    fast = fast.next;

    while (fast != null) {
        fast = fast.next;
        slow = slow.next;
    }

    slow.next = slow.next.next;

    return dummyHead.next;
};

面试题 02.07. 链表相交

142.环形链表II