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

牛群的重新排列

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;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-15 17:17
听说过付费实习,没想到这么贵啊我去,要不我给你个腰子吧
哈哈哈,你是老六:这种公司一定要注意啊,不要随便签合同,只要签了后面钱可能回不来,而且你通过法律途径也弄不回
点赞 评论 收藏
分享
吴offer选手:下午mt一来就告警说项目来不及,估计明天拿了权限就要参与开发了 已老实
实习生的蛐蛐区
点赞 评论 收藏
分享
06-28 22:48
已编辑
广东金融学院 Java
小浪_Coding:学院本+这俩项目不是buff叠满了嘛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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