1. <?php
    2. Class ListNode {
    3. /** @var int $val */
    4. public $val = 0;
    5. /** @var ListNode $next */
    6. public $next;
    7. public function __construct($val) {
    8. $this->val = $val;
    9. }
    10. }
    11. class Solution {
    12. /**
    13. * $dummy->1->2->3->4->5
    14. *
    15. * $dummy->2->1->3->4->5
    16. *
    17. * 2->1->4->3->5
    18. * @param ListNode $head
    19. * @return ListNode
    20. */
    21. public function swapPairs(ListNode $head) : ListNode {
    22. $dummyHead = new ListNode(0);
    23. $dummyHead->next = $head;
    24. // 变量赋值对象时,是浅拷贝(引用赋值)
    25. $current = $dummyHead;
    26. while ($current->next && $current->next->next) {
    27. $node1 = $current->next;
    28. $node2 = $node1->next;
    29. $nextNode = $node2->next;
    30. $node1->next = $nextNode;
    31. $node2->next = $node1;
    32. $current->next = $node2;
    33. $current = $node1;
    34. }
    35. return $dummyHead->next;
    36. }
    37. }
    38. $head = new ListNode(1);
    39. $head->next = new ListNode(2);
    40. $head->next->next = new ListNode(3);
    41. $head->next->next->next = new ListNode(4);
    42. $head->next->next->next->next = new ListNode(5);
    43. $cls = new Solution();
    44. $r = $cls->swapPairs($head);
    45. print_r($r);