My Java AC solution


  • 0
    K

    '''
    public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
    if (head == null || head.next == null) {
    return head;
    }
    int len = length(head);
    int times = len/k;
    ListNode dummy = new ListNode(-1);
    dummy.next = head;
    ListNode pre = dummy;
    while (times-- > 0) {
    ListNode preCur = pre.next;
    ListNode cur = preCur.next;
    int tmpK = k;
    while (tmpK-- > 1) {
    preCur.next = cur.next;
    cur.next = pre.next;
    pre.next = cur;
    cur = preCur.next;
    }
    pre = preCur;
    }
    return dummy.next;
    }

    int length(ListNode head) {
        int count = 0;
        ListNode cur = head;
        while (cur != null) {
            cur = cur.next;
            count++;
        }
        return count;
    }
    

    }
    '''

    Spoiler


Log in to reply
 

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