25. Reverse Nodes in k-Group

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(k <= 1) return head;
        ListNode dummy = new ListNode(0, head);
        ListNode tail = dummy;
        while(tail.next != null) {
            int count = k;
            ListNode temp = tail;
            tail = tail.next;
            ListNode temp2 = tail;
            while(temp2 != null && count > 0) {
                temp2 = temp2.next;
                count--;
            }
            if(count > 0) return dummy.next;
            count = k-1;
            while(count > 0) {
                ListNode cur = tail.next;
                tail.next = cur.next;
                cur.next = temp.next;
                temp.next = cur;
                count--;
            }
        }
        return dummy.next;
    }
}

你可能感兴趣的:(leetcode)