/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode ReverseKGroup(ListNode head, int k) { if(head == null || head.next == null || k == 1){ return head; } var len = 0; var h = head; while(head != null){ head = head.next; len ++; } if(k > len){ return h; } ListNode pre = null; ListNode newHead = null; while(len >= k) { ReverseKNodes(ref h, k, ref pre); if(pre == null){ newHead = h; pre = h; for(var i =0 ;i < k-1; i++){ pre = pre.next; } }else{ for(var i = 0;i < k;i++){ pre = pre.next; } } for(var i = 0;i < k;i++){ h = h.next; } len -= k; } return newHead; } private void ReverseKNodes(ref ListNode n, int k, ref ListNode preNode) { var stack = new Stack(); for(var i = 0;i < k; i++){ stack.Push(n.val); n = n.next; } ListNode end = n; ListNode tmp = new ListNode(stack.Pop()); var tmpHead = tmp; while(stack.Count > 0){ var n1 = new ListNode(stack.Pop()); tmp.next = n1; tmp = tmp.next; } tmp.next = end; if(preNode != null){ n = tmpHead; preNode.next = tmpHead; }else{ n = tmpHead; } } }