关于leetcode:25-Reverse-Nodes-in-kGroup

11次阅读

共计 616 个字符,预计需要花费 2 分钟才能阅读完成。

/**
 * 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;
    }
}
正文完
 0