LeetCode每日一练【24】
Swap Nodes in Pairs
我的提交
介绍
罗里吧嗦
思路
- 循环遍历链表
- 交换两个节点
- 找到下两个节点,继续进行交换
代码
/*
 * @Author: fox
 * @Date: 2022-05-05 08:01:04
 * @LastEditors: fox
 * @LastEditTime: 2022-05-05 10:04:31
 * @Description: https://leetcode.com/problems/swap-nodes-in-pairs/
 */
/**
 * @description: Runtime: 84.28%  Memory Usage: 50.14%
 * @param {*}
 * @return {*}
 */
class ListNode {
    constructor (val, next) {
        this.val = (val === undefined ? 0 : val);
        this.next = (next === undefined ? null : next);
    }
}
const swapPairs = (head) => {
    if (!head || head.length === 0) return null;
    if (head.length === 1) return head[0];
    const listnode = new ListNode(0, head);
    let pre = listnode;
    let cur = pre.next.next;
    while (pre && cur) {
        // 1. 节点交换
        pre.next.next = cur.next;
        cur.next = pre.next;
        pre.next = cur;
        // 2. 移动节点
        if (!cur.next.next || !cur.next.next.next) break;
        pre = cur.next;
        cur = pre.next.next;
    }
    return listnode.next;
}
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号