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. ListNode dummyHead = new ListNode(0,head);
    14. ListNode pre = dummyHead;
    15. //1 分组,往后走K-1步,找到一组 找到一组内的head 和 end
    16. while(head != null){
    17. ListNode groupEnd = getGroupEnd(head,k-1);
    18. if(groupEnd == null){
    19. break;
    20. }
    21. //2 每一组内部要进行翻转
    22. ListNode nextGroupHead = groupEnd.next;
    23. reverseList(head,nextGroupHead);
    24. //3 更新每组前一组后一组的边
    25. //接边
    26. pre.next = groupEnd;
    27. head.next = nextGroupHead;
    28. //移动pre 和 head
    29. pre = head;
    30. head = nextGroupHead;
    31. }
    32. return dummyHead.next;
    33. }
    34. //获取一个组的末尾结点
    35. ListNode getGroupEnd(ListNode head,int step){
    36. for(int i = 0;i < step;i++){
    37. if(head == null){
    38. return null;
    39. }
    40. head = head.next;
    41. }
    42. return head;
    43. }
    44. public ListNode reverseList(ListNode head, ListNode end) {
    45. //使用三个指针记录,pre 前面的节点,cur 当前节点,next 下一个节点
    46. ListNode pre = head;
    47. ListNode cur = head.next;
    48. while(cur != end){
    49. ListNode next = cur.next;
    50. cur.next = pre;
    51. pre = cur;
    52. cur = next;
    53. }
    54. return pre;
    55. }
    56. }