Reverse Linked List II
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.Basic Idea:
Java Code:
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
// find mth first
ListNode preHead = dummy;
for (int i = 0; i < m - 1; ++i) preHead = preHead.next;
ListNode mth = preHead.next;
// reverse mth - nth
ListNode curr = mth;
ListNode prev = null;
ListNode next = null;
for (int i = 0; i < n - m + 1; ++i) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
ListNode nth = prev;
ListNode tailNext = curr;
// 连接
preHead.next = nth;
mth.next = tailNext;
return dummy.next;
}
}Python Code
Java Code:
Last updated