题解 | #牛群的重新排列#

牛群的重新排列

https://www.nowcoder.com/practice/5183605e4ef147a5a1639ceedd447838

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param left int整型 
     * @param right int整型 
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int left, int right) {
        // write code here
        if(left == right) return head;
        ListNode cur = new ListNode(501);
        cur.next = head;
        ListNode start = cur;
        ListNode end = null;
        head = cur;
        int index = 1;
        while(cur != null) {
            if(index == left) 
                start = cur;
            if(index == right + 1) {
                end = cur.next;
                break;
            }
            index++;
            cur =  cur.next;
        }
        reverse(start.next, right - left, start).next = end;
        
        return head.next;
    }
    public ListNode reverse(ListNode node, int end, ListNode start) {
        if(end == 0) {
            start.next = node;
            return node;
        }
        reverse(node.next, end - 1, start).next = node;
        return node;
    }
}

全部评论

相关推荐

不会hc都被抢完了吧
投递深圳市新凯来技术等公司10个岗位
点赞 评论 收藏
分享
09-02 11:14
已编辑
四川大学 Java
吴offer选手:这种面试是最烦的,学不到东西,然后还被挂的莫名其妙。之前看到一种说法是面试官如果不想要你了,就会问一些很简单的问题,防止你举报他
点赞 评论 收藏
分享
我只是一个小白菜:我还用不惯m4,也是山猪吃不了细糠了
投递字节跳动等公司10个岗位
点赞 评论 收藏
分享
海康威视已挂,是非对错我已无心关心
不想上班的大西瓜:为什么我投了10多天还在简历评估啊一点消息都没有
投递海康威视等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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