题解 | #牛群的重新排列#
牛群的重新排列
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;
}
}
