题解 | #链表中的节点每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){
            return head;
        }
        ListNode end = head,begin = head;
        for(int i = 0 ; i < k; i++){
            if(end == null){ return head;}
            end = end.next;
        }
        ListNode newHead = reverseAToB(begin,end);
        begin.next = reverseKGroup(end,k);
        return newHead;

    }

    public ListNode reverseAToB(ListNode a,ListNode b){
        ListNode pre = null,cur = a,nxt = a;
        while(cur != b){
            nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }
}
全部评论

相关推荐

程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
2025-11-07 14:38
已编辑
东华理工大学 Java
糠茹频频影:寒假实习hc还是有的,继续投吧,至少1000+沟通以上
Java求职圈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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