Could anyone give me some suggestion about my coding style and improve it, thanks!


  • 1
    R

    I know my code is so long.
    I hope someone give me some suggestion to shorter it.
    And I am still student and never work in industry before, Could you give me some suggestion from the industrial view, how to improve my coding style

    public class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            if(head == null || k == 0)
                return head;
            
     //use a preHead node to avoid move the head later.
            ListNode preHead = new ListNode(0);
            preHead.next = head;
    //preStart means the one before the start of the reversed group
            ListNode preStart = preHead;
    //start is the start node of the reversed group
            ListNode start = preStart.next;
    //end is the end node of the reversed group
            ListNode end;
    //tail is the next node of the reversed group
            ListNode tail;
    
            ListNode pointer = head;
            int count = 0;
            
            while(pointer != null){
                if(++count == k){
                    end = pointer;
                    tail = end.next;
                    ListNode newStart = reverse(start, tail);
                    preStart.next = end;
                    preStart = newStart;
                    start = preStart.next;
                    count = 0;
                    pointer = start;
                }else
                    pointer = pointer.next;
            }
            return preHead.next;
        }
    
        private ListNode reverse(ListNode node, ListNode tail){
            if(node == tail) return tail;
            ListNode next = reverse(node.next, tail);
            if(next == tail) return node;
            node.next = tail;
            next.next = node;
            return node;
        }
    }

Log in to reply
 

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