题解 | #牛群的重新排列#
牛群的重新排列
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) {
if (left == right)return head;
// write code here
ListNode pre = null;
ListNode end = head;
ListNode cur = head;
ListNode pointpre = null;
for (int i = 1; i < left; i++) {
if(pointpre==null){pointpre=head;continue;}
pointpre=pointpre.next;
}
for (int i = 0; i < right; i++) {
end = end.next;
}
pre = end;
if(pointpre!=null){
cur = pointpre.next;
}
while (cur != end) {
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
if (pointpre == null) {
return pre;
} else {
pointpre.next = pre;
}
head.next=pointpre;
return head;
}
}
查看16道真题和解析