public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m >= n || head == null) {
return head;
}
// create a dummy node b/c m may be 1, thus we can't find node before reverse position
ListNode dummy = new ListNode(0);
dummy.next = head;
// find the node beofre the reverse position
ListNode left = dummy;
for (int i=1; i<m; i++) {
left = left.next;
}
// do the reverse for the list starting at left.next
ListNode prev = left.next;
ListNode curr = prev.next;
ListNode next = null;
// only change m-n links
for (int i=m; i<n; i++) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
// link the head and tail
left.next.next = curr;
left.next = prev;
return dummy.next;
}
}
Leetcode 92. Reverse Linked List II
最新推荐文章于 2022-10-08 18:10:16 发布