题意:

image.png

图示:

递归图示:

链表两两交换.jpg

解题思路:

  1. 思路:
  2. 1. for 循环找到第k个节点
  3. 2. 从头到k个节点,进行反转,并返回翻转后的头结点newnode
  4. 3. 继续对下一轮k个节点反转;
  5. 5. 将上一轮反转后的尾节点,指向下一轮反转的头节点,确保每一轮反转后节点相连;
  6. 6. 最后返回newnode头节点

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. function reverseKGroup($head, $k) {
  11. $node = $head;
  12. for ($i = 0; $i < $k; $i++) {
  13. if (!$node) return $head;
  14. $node = $node->next;
  15. }
  16. $newHead = $this->reverse($head, $node);
  17. $head->next = $this->reverseKGroup($node, $k);
  18. return $newHead;
  19. }
  20. function reverse($start, $end) {
  21. $pre = null;
  22. while ($start != $end) {
  23. $next = $start->next;
  24. $start->next = $pre;
  25. $pre = $start;
  26. $start = $next;
  27. }
  28. return $pre;
  29. }
  30. }

GO代码实现:

  1. /**
  2. * Definition for singly-linked list.
  3. * type ListNode struct {
  4. * Val int
  5. * Next *ListNode
  6. * }
  7. */
  8. func reverseKGroup(head *ListNode, k int) *ListNode {
  9. node := head
  10. for i := 0; i < k; i++ {
  11. if node == nil { return head }
  12. node = node.Next
  13. }
  14. newHead := reverse(head, node)
  15. head.Next = reverseKGroup(node, k)
  16. return newHead
  17. }
  18. func reverse(head, tail *ListNode) *ListNode {
  19. p, q := head, head.Next
  20. p.Next = tail
  21. for q != tail {
  22. r := q.Next
  23. q.Next = p
  24. p = q
  25. q = r
  26. }
  27. return p
  28. }