题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
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) return head;
//移动前节点
int step = n-m;
ListNode front = head;
int i = 1;
while(i <= step){
front = front.next;
i++;
}
//定位后节点
i = 1;
ListNode behind = head;
ListNode pre = null;
while(i < m){
i++;
front = front.next;
pre = behind;
behind = behind.next;
}
//获取起始位置
if(m == 1) pre = null;
ListNode start = pre,end = front.next;
pre = end;
//反转链表
while(behind != null && behind.next != end){
ListNode temp = behind.next;
behind.next = pre;
pre = behind;
behind = temp;
}
behind.next = pre;
//判断要返回的头节点位置
if(start != null) {
start.next = behind;
return head;
}else return behind;
}
}