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

牛群的重新排列

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

全部评论

相关推荐

ldf李鑫:不说公司名祝你以后天天遇到这样的公司
点赞 评论 收藏
分享
04-17 18:32
门头沟学院 Java
野猪不是猪🐗:他跟你一个学校,你要是进来之后待遇比他好,他受得了?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务