C# Solution Beating 100% with readable variable names


  • 0
    5

    The key is to keep building current group by tracking the previous element of the developing group (tracked by groupSentry), the current element of the group (tracked by curr) and the total count of elements in this group so far (tracked by count). If we have counted enough (k) elements, we slice the group out of the entire list (by setting null on the last element's next field) and send it for normal reversing.

    /**
     * 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) return head;
            
            var sentry = new ListNode(0) { next = head };
            
            var count = 0;
            var curr = sentry;
            var groupSentry = sentry;
            while (curr.next != null) {
                curr = curr.next;
                count++;
                
                if (count == k) {
                    var nextGroupSentry = groupSentry.next;
                    var next = curr.next;
    
                    curr.next = null;
                    groupSentry.next = Reverse(groupSentry.next);
    
                    nextGroupSentry.next = next;
                    curr = groupSentry = nextGroupSentry;
                    count = 0;
                }
            }
            
            return sentry.next;
        }
        
        private ListNode Reverse(ListNode head) {
            var sentry = new ListNode(0);
            
            var curr = head;
            while (curr != null) {
                var next = curr.next;
                
                var newNext = sentry.next;
                sentry.next = curr;
                curr.next = newNext;
                
                curr = next;
            }
            
            return sentry.next;
        }
    }
    

Log in to reply
 

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