<?phpClass ListNode { /** @var int $val */ public $val = 0; /** @var ListNode $next */ public $next; public function __construct($val) { $this->val = $val; }}class Solution { /** * $dummy->1->2->3->4->5 * * $dummy->2->1->3->4->5 * * 2->1->4->3->5 * @param ListNode $head * @return ListNode */ public function swapPairs(ListNode $head) : ListNode { $dummyHead = new ListNode(0); $dummyHead->next = $head; // 变量赋值对象时,是浅拷贝(引用赋值) $current = $dummyHead; while ($current->next && $current->next->next) { $node1 = $current->next; $node2 = $node1->next; $nextNode = $node2->next; $node1->next = $nextNode; $node2->next = $node1; $current->next = $node2; $current = $node1; } return $dummyHead->next; }}$head = new ListNode(1);$head->next = new ListNode(2);$head->next->next = new ListNode(3);$head->next->next->next = new ListNode(4);$head->next->next->next->next = new ListNode(5);$cls = new Solution();$r = $cls->swapPairs($head);print_r($r);