题目
法1:迭代写法
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode preStart = dummy, postEnd = dummy;
while (left > 1) {
preStart = preStart.next;
--left;
}
while (right >= 0) {
postEnd = postEnd.next;
--right;
}
ListNode pre = null, cur = preStart.next;
while (cur != postEnd) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
preStart.next = pre;
cur = pre;
while (cur.next != null) {
cur = cur.next;
}
cur.next = postEnd;
return dummy.next;
}
}