From 2d6b09b66a0fea7412ab40002cdce4eb02da2854 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=B4=E7=83=A8?= Date: Wed, 10 Aug 2022 11:19:58 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200024.=E4=B8=A4=E4=B8=A4?= =?UTF-8?q?=E4=BA=A4=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82?= =?UTF-8?q?=E7=82=B9=20PHP=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0024.两两交换链表中的节点.md | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 4b4b39e7..5b73fb05 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -336,5 +336,48 @@ object Solution { } ``` +PHP: +```php +//虚拟头结点 +function swapPairs($head) { + if ($head == null || $head->next == null) { + return $head; + } + + $dummyNode = new ListNode(0, $head); + $preNode = $dummyNode; //虚拟头结点 + $curNode = $head; + $nextNode = $head->next; + while($curNode && $nextNode) { + $nextNextNode = $nextNode->next; //存下一个节点 + $nextNode->next = $curNode; //交换curHead 和 nextHead + $curNode->next = $nextNextNode; + $preNode->next = $nextNode; //上一个节点的下一个指向指向nextHead + + //更新当前的几个指针 + $preNode = $preNode->next->next; + $curNode = $nextNextNode; + $nextNode = $nextNextNode->next; + } + + return $dummyNode->next; +} + +//递归版本 +function swapPairs($head) +{ + // 终止条件 + if ($head === null || $head->next === null) { + return $head; + } + + //结果要返回的头结点 + $next = $head->next; + $head->next = $this->swapPairs($next->next); //当前头结点->next指向更新 + $next->next = $head; //当前第二个节点的->next指向更新 + return $next; //返回翻转后的头结点 +} +``` + -----------------------