2014年5月12日星期一

Recursive Loop Solution - Reverse Nodes in k-Group

Take the K list, and set next = recursive call instead of iteration, largely simplify the program. Reverse the K. Watch when list < K, return head.

When realized iteration is a mess, make a decision to use Recursive approach.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || head.next == null || k < 2){
            return head;
        }
        ListNode newHead = new ListNode(Integer.MIN_VALUE);
        newHead.next = head;
        ListNode kNext = newHead.next;
        int index = 0;
        while(index < k && kNext != null){
            kNext = kNext.next;
            index++;
        }
        if(index < k){
            return newHead.next;
        }
        ListNode lp = head;
        ListNode next = reverseKGroup(kNext, k);
        while(lp.next != kNext){
            ListNode temp = lp.next;
            lp.next = next;
            next = lp;
            lp = temp;
        }
        newHead.next = lp;
        lp.next = next;
        return newHead.next;
    }
}

没有评论: