From 8cf3fabb60a29966bb725b223ada9d92d7aa5bb1 Mon Sep 17 00:00:00 2001 From: Aaron-Lin-74 <84072071+Aaron-Lin-74@users.noreply.github.com> Date: Sat, 5 Mar 2022 11:41:05 +1100 Subject: [PATCH] =?UTF-8?q?Update=200024.=E4=B8=A4=E4=B8=A4=E4=BA=A4?= =?UTF-8?q?=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82=E7=82=B9?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TypeScript version code that better matches your c++ code example. --- .../0024.两两交换链表中的节点.md | 40 +++++++------------ 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index bf1fd5e1..ce75e0d7 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -254,32 +254,20 @@ TypeScript: ```typescript function swapPairs(head: ListNode | null): ListNode | null { - /** - * 初始状态: - * curNode -> node1 -> node2 -> tmepNode - * 转换过程: - * curNode -> node2 - * curNode -> node2 -> node1 - * curNode -> node2 -> node1 -> tempNode - * curNode = node1 - */ - let retNode: ListNode | null = new ListNode(0, head), - curNode: ListNode | null = retNode, - node1: ListNode | null = null, - node2: ListNode | null = null, - tempNode: ListNode | null = null; - - while (curNode && curNode.next && curNode.next.next) { - node1 = curNode.next; - node2 = curNode.next.next; - tempNode = node2.next; - curNode.next = node2; - node2.next = node1; - node1.next = tempNode; - curNode = node1; - } - return retNode.next; -}; + const dummyHead: ListNode = new ListNode(0, head); + let cur: ListNode = dummyHead; + while(cur.next !== null && cur.next.next !== null) { + const tem: ListNode = cur.next; + const tem1: ListNode = cur.next.next.next; + + cur.next = cur.next.next; // step 1 + cur.next.next = tem; // step 2 + cur.next.next.next = tem1; // step 3 + + cur = cur.next.next; + } + return dummyHead.next; +} ``` Kotlin: