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: