publicListNodereverseList(ListNode head){ListNode cur = head;ListNode pre =null;while(cur !=null){ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;}return pre;}
publicListNodereverseKGroup(ListNode head,int k){ListNode dummy =newListNode(-1);
dummy.next = head;ListNode pre = dummy;ListNode end = dummy;while(end !=null){for(int i =0; i < k && end !=null; i++){
end = end.next;}if(end ==null){break;}ListNode next = end.next;ListNode start = pre.next;
end.next =null;
pre.next =reverse(start);
start.next = next;
pre = start;
end = start;}return dummy.next;}privateListNodereverse(ListNode head){ListNode pre =null;ListNode cur = head;while(cur !=null){ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;}return pre;}
另外一个类似的题目是 最后不足K个的时候也要翻转
//每K个翻转, 最后不足K也要翻转==================publicListNodereverseKGroupnotK(ListNode head,int k){ListNode dummy =newListNode(-1);
dummy.next = head;ListNode pre = dummy;ListNode end = dummy;while(end !=null){for(int i =0; i < k && end !=null; i++){
end = end.next;}if(end ==null){ListNode start = pre.next;
pre.next =reverse(start);break;}ListNode next = end.next;ListNode start = pre.next;
end.next =null;
pre.next =reverse(start);
start.next = next;
pre = start;
end = start;}return dummy.next;}