public ListNode reverseBetween(ListNode head, int left, int right) {
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;
for(int i = 0; i < right - left; i++) {
ListNode next = cur.next;
cur.next = next.next;
next.next = pre.next;
pre.next = next;
}
return dummyNode.next;
}
1.2穿针引线法
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
for(int i = 0; i < left - 1; i++) {
pre = pre.next;
}
ListNode start = pre.next;
ListNode end = start;
for(int i = left; i < right; i++) {
end = end.next;
}
ListNode succ = end.next;
end.next = null;
reverseList(start);
pre.next = end;
start.next = succ;
return dummyNode.next;
}
public void reverseList(ListNode node) {
ListNode pre = null;
ListNode cur = head;
while(cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
}