【递归解】

链表中的节点每k个一组翻转

http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
      public ListNode reverseKGroup (ListNode head, int k) {
        ListNode flag = head;
        int start = 1;
        int end = k;
        int len = 0;
        while(flag != null){
            flag = flag.next;
            len++;
        }
        if(len < k){
            return head;
        }
        while(len - start > 0 && (len - start + 1) >= k){
            head = reverseM2N(head,start,end);
            start = end + 1;
            end = k + start - 1;
        }
        return head;
    }

    public ListNode reverseM2N(ListNode head,int m,int n){
        if(m == 1){
            return reverseN(head,n);
        }
        head.next = reverseM2N(head.next,m - 1,n - 1);//这里n还是得减1得和m一起减
        return head;
    }

    ListNode lastNext;
    public ListNode reverseN(ListNode head,int tmp){
        // write code here
        if(tmp == 1){
            lastNext = head.next;
            return head;
        }
        ListNode newNode = reverseN(head.next,tmp-1);
        head.next.next = head;
        head.next = lastNext;
        return newNode;
    }
}
全部评论

相关推荐

尊尼获获:闺蜜在哪?
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务