24. 两两交换链表中的节点(JS实现)

1 题目

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.

2 思路

这道题思路是通过循环的方法依次交换相邻的两个节点,并将当前循环交换后第二个节点与下个循环的节点连接起来

3代码

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function(head) {
    function swap(node1, node2) {   //交换两个节点,返回原来的第1个节点和第3个节点
        var thirdNode = node2.next;  //如果此时不保存第三个节点,则交换后,链接就断了
        node2.next = node1;
        node1.next = null;
        return [node1, thirdNode];
    }

    if (!head || !head.next) return head;

    var newHead = head.next;
    var node;
    
    while(head && head.next) {
        if (node) node.next = head.next;   //上个循环的节点在此进行连接
        [node, head] = swap(head, head.next);
        if (!head || !head.next) node.next = head;   //如果第三个节点是最后一个节点,直接连接上
    }

    return newHead;
};

猜你喜欢

转载自blog.csdn.net/zjw_python/article/details/106482305