LeetCode每日一练【24】
<h1 id="swap-nodes-in-pairs">Swap Nodes in Pairs</h1><h2 id="我的提交">我的提交</h2>
<h3 id="介绍">介绍</h3>
<p>罗里吧嗦</p>
<h3 id="思路">思路</h3>
<ol>
<li>循环遍历链表</li>
<li>交换两个节点</li>
<li>找到下两个节点,继续进行交换</li>
</ol>
<h3 id="代码">代码</h3>
<pre><code class="language-js">/*
* @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;
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;
}
</code></pre><br><br>
来源:https://www.cnblogs.com/mapodoufu/p/16223683.html
頁:
[1]