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.
一定要注意边界条件,处理问题时,一定要首先判断是否越界然后再使用。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null || head.next == null || m >= n) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
int index = 0;
ListNode pre = null;
ListNode node = null;
ListNode post = null;
for (int i = 0; i < n; i++) {
if (head == null) {
return null;
}
if (index == m - 1) {
pre = head;
} else if (index == m) {
node = head;
}
index++;
head = head.next;
}
if (head == null) {
return null;
}
post = head.next;
head.next = null;
pre.next = reverse(node);
head = getTail(dummy);
head.next = post;
return dummy.next;
}
private ListNode reverse(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}
private ListNode getTail(ListNode head) {
while (head.next != null) {
head = head.next;
}
return head;
}
}