链表内指定区间反转
题目描述
思路
代码
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(head==null) return null;
ListNode res = new ListNode(-1);
res.next = head;
ListNode pre = res;
//移动指针到m-1的位置
for(int i=1; i<m; i++){
pre = pre.next;
}
//反转后的尾指针,总是之后循环中总是指向当前节点的下一个节点
ListNode tail = pre.next;
ListNode cur = null;
for(int i=m; i<n; i++){
//m+1位置开始,通过tail获取当前操作的节点
cur = tail.next;
//尾结点存储下一次循环操作的节点
tail.next = cur.next;
//反转
cur.next = pre.next;
//指向当前节点,最后反转后的头
pre.next = cur;
}
return res.next;
}
}