Concise c# solution


  • 0
    M
    public class Solution {
        public ListNode ReverseKGroup(ListNode head, int k) {
            ListNode final = new ListNode(0);
            ListNode prev = null, tail = null, prevTail = final;
            
            for(int i = 0; head != null; i = (i+1)%k) {
                var next = head.next;
                head.next = prev;
                
                if(i == 0) {
                    tail = head;
                    head.next = null;
                } else {
                    head.next = prev;
                }    
                
                if(i == k-1) {
                    prevTail.next = head;
                    prevTail = tail;
                } else if(next == null) {
                    prevTail.next = ReverseKGroup(head, i+1);
                }
                
                prev = head;
                head = next;
            }
            
            return final.next;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.