An accepted C# iterative solution.


  • 0
    S
    /**
     * 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 (k <= 1 || head == null || head.next == null)
            {
                return head;
            }
    
            var start = head;
            var current = start;
            ListNode first = null;
            while (current != null)
            {
                var pre = new ListNode(-1);
                pre.next = current;
                var node = pre;
                int n = k;
                while (node != null && n > 0)
                {
                    node = node.next;
                    n--;
                }
                if (node == null)
                {
                    return start;
                }
                if (first != null)
                {
                    first.next = node;
                }
                var kthNode = node.next;
                first = current;
                while (current != kthNode)
                {
                    var next = current.next;
                    current.next = node;
                    node = current;
                    current = next;
                }
                first.next = current;
                if (start == head)
                {
                    start = node;
                }
            }
    
            return start;
        }
    }
    

Log in to reply
 

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