Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
題意:反轉(zhuǎn)鏈表的指定一段踢故。
思路:這道題是Reverse Linked List的followup,把反轉(zhuǎn)整個鏈表限定為反轉(zhuǎn)指定一段佑笋±胙可以把反轉(zhuǎn)的解法套在指定范圍上稳懒,反轉(zhuǎn)之后還要把它和原來的兩端連接起來,所以需要記錄一下兩端連接的節(jié)點,以及反轉(zhuǎn)后的這段鏈表的頭尾節(jié)點嘴瓤。
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null || head.next == null || m < 0 || n <= m) {
return head;
}
ListNode root = new ListNode(0);
root.next = head;
//連接反轉(zhuǎn)段的端點
ListNode left = root;
ListNode right = new ListNode(0);
//反轉(zhuǎn)段的左右端點
ListNode rLeft = new ListNode(0);
ListNode rRight = new ListNode(0);
//反轉(zhuǎn)需要的兩個指針
ListNode pre = new ListNode(0);
ListNode cur = new ListNode(0);
for (int i = 0; i < m - 1; i++) {
left = left.next;
}
rRight = left.next;
pre = left.next;
cur = pre.next;
for (int i = 0; i < n - m; i++) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
rLeft = pre;
right = cur;
left.next = rLeft;
rRight.next = right;
return root.next;
}