题目描述:
    给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

    k 是一个正整数,它的值小于或等于链表的长度。

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

    链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group

    代码实现:

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode() {}
    7. * ListNode(int val) { this.val = val; }
    8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    9. * }
    10. */
    11. class Solution {
    12. public ListNode reverseKGroup(ListNode head, int k) {
    13. // 分组翻转
    14. ListNode dummyHead = new ListNode(0);
    15. dummyHead.next = head;
    16. ListNode pre = dummyHead;
    17. while(head != null) {
    18. ListNode tail = pre;
    19. int step = k;
    20. // k步一组
    21. while(step > 0) {
    22. step--;
    23. tail = tail.next;
    24. if (tail == null) { // 最后不足k的一组
    25. return dummyHead.next;
    26. }
    27. }
    28. // 记录下一个结点,防止断链
    29. ListNode next = tail.next;
    30. // 翻转
    31. reversePartOfListNode(head,tail);
    32. ListNode tempHead = tail;
    33. ListNode tempTail = head;
    34. // 重新接链
    35. pre.next = tempHead;
    36. tempTail.next = next;
    37. // 移动结点
    38. pre = tempTail;
    39. head = tempTail.next;
    40. }
    41. return dummyHead.next;
    42. }
    43. // 翻转部分链表
    44. public void reversePartOfListNode(ListNode head, ListNode tail) {
    45. ListNode pre = tail.next;
    46. ListNode cur = head;
    47. while(pre != tail) {
    48. ListNode next = cur.next;
    49. cur.next = pre;
    50. pre = cur;
    51. cur = next;
    52. }
    53. }
    54. }