牛课题霸每日一题NC50题解Java描述
思路: 递归翻转。
代码:
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ public ListNode reverseKGroup (ListNode head, int k) { // write code here if(head == null){ return null; } ListNode dummyHead = new ListNode(0), prev = dummyHead, curr = head, next = head.next, He = head; dummyHead.next = head; int count = 0; while(head != null && count < k){ ++count; head = head.next; } if(count != k){ return dummyHead.next; } while(curr != head){ curr.next = prev; prev = curr; curr = next; if(curr != null){ next = curr.next; } } dummyHead.next = prev; He.next = reverseKGroup(head, k); return dummyHead.next; } }