题解 | #寻找峰值#
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
1、固定pre的位置在m的前一位,之后将反转区间内的每一个结点经过头插法插入到反转区间的第一个结点;
2、此操作需要定义一个辅助结点temp操作;
3、最好定义一个虚拟头结点dummyNode;
自己动手画一画就很好理解了。
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
//定义虚拟头结点
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode;
//找到pre结点的位置
for(int i=0; i<m-1;i++){
pre = pre.next;
}
//定义当前操作结点cur和辅助结点temp
ListNode cur = pre.next;
ListNode temp;
//将反转区间内的结点头插到区间开始的位置m
for(int i=0; i<n-m; i++){
temp = cur.next; //temp指向需要移动到位置m的结点
cur.next = temp.next; //保存temp后面的结点
temp.next = pre.next; //temp指向当前位置m的结点
pre.next = temp; //pre指向temp,即temp变为位置m的结点了
}
return dummyNode.next;
}
}
