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

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

https://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 null;
        ListNode tail = head;
        for(int i = 1;i < k && tail != null;i++){
            tail = tail.next;
        }
        if(tail == null) return head;
        ListNode next = tail.next;
        reverse(head,tail);
        head.next = reverseKGroup(next,k);
        return tail;
    }
    public void reverse(ListNode head,ListNode tail){
        ListNode dummy = null;
        ListNode last = tail.next;
        while(head != last){
            ListNode next = head.next;
            head.next = dummy;
            dummy = head;
            head = next;
        }
    }
}
全部评论

相关推荐

09-29 16:59
已编辑
门头沟学院 Java
牛客96609213...:疯狂背刺,之前还明确设置截止日期,还有笔试,现在一帮人卡在复筛,他反而一边开启扩招,还给扩招的免笔试,真服了,你好歹先把复筛中的给处理了再说
投递大疆等公司10个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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