题目描述
AC代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null||m==n)
return head;
//为了避免头节点也被翻转,定义个虚拟头节点
ListNode dummy=new ListNode(-1);
dummy.next=head;
//先找到第m个节点b的前一个节点a和第n个节点c
ListNode a=dummy,c=dummy;
for(int i=0;i<m-1;i++)
a=a.next;
for(int i=0;i<n;i++)
c=c.next;
ListNode b=a.next;
ListNode d=c.next;
for(ListNode p=b,q=b.next;q!=d;){
ListNode tmp=q.next;
q.next=p;
p=q;
q=tmp;
}
b.next=d;
a.next=c;
return dummy.next;
}
}