第一种方法,使用双指针,头插法
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
// 设置 dummyNode 是这一类问题的一般做法
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode;
for (int i = 0; i < left - 1; i++) {
pre = pre.next;
}
ListNode cur = pre.next;
ListNode next;
for (int i = 0; i < right - left; i++) {
next = cur.next;
cur.next = next.next;
next.next = pre.next;
pre.next = next;
}
return dummyNode.next;
}
}
第二种,使用递归实现
class Solution {
static ListNode successor = null;
public static ListNode reverseN(ListNode head, int n) {
if(n==1){
successor=head.next;
return head;
}
ListNode last=reverseN(head.next,n-1);
head.next.next=head;
head.next=successor;
return last;
}
public static ListNode reverseBetween(ListNode head, int m, int n) {
if(m==1){
return reverseN(head,n);
}
head.next=reverseBetween(head.next,m-1,n-1);
return head;
}
public static void main(String[] args) {
ListNode listNode1=new ListNode(1);
ListNode listNode2=new ListNode(2);
ListNode listNode3=new ListNode(3);
ListNode listNode4=new ListNode(4);
listNode1.next=listNode2;
listNode2.next=listNode3;
listNode3.next=listNode4;
listNode4.next=null;
ListNode result=reverseBetween(listNode1,1,4);
while (result!=null){
System.out.print(result.val+"-->");
result=result.next;
}
}
}