题解 | #链表中的节点每k个一组翻转#

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

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

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) {
        ListNode result = null;
        if(head == null){
            return result;
        }
        // write code here
        int kk = 0;
        ListNode node = head;
        ListNode dumpHead = head;
        ListNode dumpCur = dumpHead;
        ListNode lastEnd = null;

        while(node!=null){

            if(kk==k){
                dumpCur.next =null;
                ListNode tmpResult = reverse(dumpHead);
                if(lastEnd == null){
                    lastEnd = new ListNode(-1);
                    result = tmpResult;
                }
                lastEnd.next = tmpResult;
                lastEnd = dumpHead;
                dumpHead = node;
                kk=0;
            }
            dumpCur= node;
            node = node.next;
            kk++;
        }
        ListNode tmpResult = null;
        dumpCur.next =null;
        if(kk==k){
            tmpResult = reverse(dumpHead);
        }else{
            tmpResult = dumpHead;
        }        
        if(lastEnd == null){
            lastEnd = new ListNode(-1);
            result = tmpResult;
        }
        lastEnd.next = tmpResult;

        return result;
    }
    
    private ListNode reverse(ListNode head){
        if(head == null || head.next==null){
            return head;
        }
        ListNode next = head.next;
        ListNode newHead = reverse(head.next);
        next.next = head;
        head.next = null;
        return newHead;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务