题解 | #链表中的节点每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) {
        // write code here
        if(head ==null || head.next==null) return head;
        ListNode tail = head;
        ListNode begin = tail;
        for(int i=0;i<k;i++){
            if(tail==null) return head;
            tail = tail.next;
        }
        for(int i=0;i<k;i++){
            if(i==k-1){
                begin.next = null;
            }else{
                begin = begin.next;
            }
        }
        ListNode newHead = reverse(head);
        head.next = reverseKGroup(tail,k);
        return newHead;
        
    }
    
    public ListNode reverse(ListNode head){
        ListNode cur = head;
        ListNode pre = null;
        while(cur!=null){
            ListNode tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
}
全部评论

相关推荐

Java面试先知:我也是和你一样的情况,hr 说等开奖就行了
点赞 评论 收藏
分享
10-01 09:50
门头沟学院 Java
肖先生~:这个人真的很好,点赞
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务