mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
@ -337,5 +337,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; //返回翻转后的头结点
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user