题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
//本题主要是对边界的把握,先定义好间隔节点 first,end, 然后移动M-1次。然后就需要判断一些异常情况,如果m=1呢?n等于长度呢?
public class Solution {
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
public ListNode reverseBetween (ListNode head, int m, int n) {
// write code here
if(m == n || head == null ||m >= n){
return head;
}
//1.定义四个节点,分别是m位置 n 位置,还有反转前后m-1 和n+1位置节点
ListNode first = head, end = head;
ListNode preFirst = null, endAfter = null;
int step = n - m;
//2.找到对应节点位置
while(step > 0){
step --;
end = end.next;
if(end == null){
return head;
}
}
//2.1 fist和end长度间距定义好了,真正开始遍历到m位置
while(m - 1 > 0){
m --;
preFirst = first;
first = first.next;
end = end.next;
if(end == null){
return head;
}
}
endAfter = end.next;
end.next = null;
reverse(first);
if(preFirst == null){
head = end;
}else{
preFirst.next = end;
}
first.next = endAfter;
return head;
}
private void reverse(ListNode slow){
ListNode pre = null, currentNode = slow;
while(currentNode != null){
ListNode next = currentNode.next;
currentNode.next = pre;
pre = currentNode;
currentNode = next;
}
}
}
面试必刷TOP101 文章被收录于专栏
面试必刷TOP101

查看22道真题和解析