Shu-How Zの小窝

Loading...

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

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

0:58:19

 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) {
    // 判断head是否为空
    if(!head)return null;
    // 将相邻的两个链表进行反转
    let ret = new ListNode(-1,head),temp=ret;
    while(temp.next&&temp.next.next){
        let pre = temp.next,cur = temp.next.next;
        temp.next = cur;
        pre.next = cur.next;
        cur.next = pre;
        temp.next = cur;
        temp = pre;
    }
    // 然后返回链表
    return ret.next;
};

let head = new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4))));
console.log(swapPairs(head));
posted @ 2026-04-27 17:56  KooTeam  阅读(5)  评论(0)    收藏  举报