给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
    k 是一个正整数,它的值小于或等于链表的长度。

    如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

    进阶:

    你可以设计一个只使用常数额外空间的算法来解决此问题吗?
    你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
    image.png
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group

    1. public class ListNode {
    2. int val;
    3. ListNode next;
    4. public ListNode(){}
    5. public ListNode(int val) {
    6. this.val = val;
    7. }
    8. public ListNode (int val, ListNode next) {
    9. this.val = val;
    10. this.next = next;
    11. }
    12. }
    13. class Solution {
    14. public ListNode reverseKGroup(ListNode head, int k) {
    15. if (head == null || head.next == null)
    16. return head;
    17. ListNode tail = head;
    18. for (int i = 0; i < k; i++) {
    19. tail = tail.next;
    20. }
    21. ListNode newHead = reverse(head, tail);
    22. head.next = reverseKGroup (tail, k);
    23. return newHead;
    24. }
    25. // 翻转链表
    26. private ListNode reverse (ListNode head, ListNode tail) {
    27. ListNode pre = null, next = null;
    28. while (head != tail) {
    29. next = head.next;
    30. head.next = pre;
    31. pre = head;
    32. head = next;
    33. }
    34. return pre;
    35. }
    36. }



    image.png