JAVA Count Length Then Reverse


  • 0
    Y
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            if(head == null || head.next == null || k == 0 || k == 1)
                return head;
            ListNode tmp = head;
            ListNode pre = new ListNode(0);
            ListNode res = pre;
            pre.next = head;
            int len = 0;
            while(tmp != null){
                len++;
                tmp = tmp.next;
            }
            if(k > len)
                return head;
            for(int i = 0; i < len / k; i++){
                head = pre.next;
                int count = 1;
                while(head != null && head.next != null && count + 1 <= k){
                    ListNode n = pre.next;
                    pre.next = head.next;
                    head.next = head.next.next;
                    pre.next.next = n;
                    count++;
                }
                pre = head;
            }
            
            
            return res.next;
        }
    }

Log in to reply
 

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