Broken Down Into Functions, Meaningful Variable Names - O(1) Space C#


  • 0
    R
    /**
     * 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) 
        {
            ListNode prevTail = null;
            ListNode resultHead = head;
    
            bool first = true;
            while (head != null)
            {
                ListNode tail = MoveOnList(head, k);
                
                if (tail == null)
                {
                    if (prevTail != null)
                    {
                        prevTail.next = head;
                    }
                    break;
                }
    
                ListNode nextHead = tail.next;
    
                ListNode revHead = null;
                ListNode revTail = null;
                ReverseLinkedListPartial(head, tail, out revHead, out revTail);
                if (first)
                {
                    resultHead = revHead;
                    first = false;
                }
                
                if (prevTail != null)
                {
                    prevTail.next = revHead;
                }
    
                prevTail = revTail;
                head = nextHead;
            }
    
            return resultHead;
        }
    
        public static ListNode MoveOnList(ListNode head, int k)
        {
            for (int i = 0; i < k - 1; ++i)
            {
                if (head == null)
                    return null;
    
                head = head.next;
            }
    
            return head;
        }
    
        public static void ReverseLinkedListPartial(ListNode head, ListNode tail, out ListNode revHead, out ListNode revTail)
        {
            ListNode tmp1 = null;
            ListNode tmp2 = null;
            ListNode curr = head;
            revTail = curr;
    
            while (tmp1 != tail)
            {
                tmp2 = curr.next;
                curr.next = tmp1;
                tmp1 = curr;
                curr = tmp2;
            }
    
            revHead = tmp1;
        }
    }
    

Log in to reply
 

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