题意:

image.png

图示:

迭代图示(1):

未命名文件 (9).jpg

递归图示(2):

未命名文件 (11).jpg

解题思路:

  1. 思路:
  2. 1. 添加虚拟头结点 dummy;
  3. 2. 定义cur指向dummy
  4. 3. 初始化 $node1 = $cur->next; $node2 = $node1->next;
  5. 4. 修改cur,node1,node2三者指向关系,如上图所示
  6. 5. 移动cur结点到下一个结点,重复上面步骤,直到条件不满足为止
  7. 6. 最后返回dummy->next

PHP代码实现:

  1. /**
  2. * Definition for a singly-linked list.
  3. * class ListNode {
  4. * public $val = 0;
  5. * public $next = null;
  6. * function __construct($val) { $this->val = $val; }
  7. * }
  8. */
  9. class Solution {
  10. /**
  11. * @param ListNode $head
  12. * @return ListNode
  13. */
  14. function swapPairs($head) {
  15. $dummy = new ListNode(0);
  16. $dummy->next = $head;
  17. $cur = $dummy;
  18. while ($cur->next && $cur->next->next) {
  19. $node1 = $cur->next;
  20. $node2 = $node1->next;
  21. $next = $node2->next;
  22. $node2->next = $node1;
  23. $node1->next = $next;
  24. $cur->next = $node2;
  25. $cur = $node1;
  26. }
  27. return $dummy->next;
  28. }
  29. function swapPairsRecursive($head) {
  30. if ($head == null || $head->next == null) return $head;
  31. $next = $head->next;
  32. $head->next = $this->swapPairsRecursive($next->next);
  33. $next->next = $head;
  34. return $next;
  35. }
  36. }

GO代码实现:

  1. /**
  2. * Definition for singly-linked list.
  3. * type ListNode struct {
  4. * Val int
  5. * Next *ListNode
  6. * }
  7. */
  8. func swapPairs(head *ListNode) *ListNode {
  9. if head == nil || head.Next == nil {
  10. return head
  11. }
  12. var dummy = &ListNode{}
  13. dummy.Next = head
  14. var cur = dummy
  15. for cur.Next != nil && cur.Next.Next != nil {
  16. node1 := cur.Next
  17. node2 := node1.Next
  18. next := node2.Next
  19. node2.Next = node1
  20. node1.Next = next
  21. cur.Next = node2
  22. cur = node1
  23. }
  24. return dummy.Next
  25. }