首先要找出颠倒的那个区间的前一节点pre和该区间的首个节点st....之后和之前的方法一样对区间内的节点进行reverse(利用两个变量记录前一节点和当前节点,循环的改变指针方向)....之后将st的next指向区间后的首个节点,将pre的next指向区间的最后一个节点即可》。。。。。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null)
{
return head;
}
ListNode stPre=null,st=head;
for(int i=1;i<m;i++ )
{
stPre = st;
st = st.next;
}
ListNode reSt = st,last=st;
for(int i=m;i<=n;i++)
{
ListNode tmp = st.next;
st.next = last;
last = st;
st = tmp;
}
reSt.next = st;
if(stPre!=null)
{
stPre.next = last;
}
else
{
head = last;
}
return head;
}
}