题解 | #链表内指定区间反转#
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
[链表内指定区间反转]
我感觉我好蠢啊...
不过还是做出来了
Java代码如下:
public class Solution { /** * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ public ListNode reverseBetween(ListNode head, int m, int n) { ListNode flag = head; ListNode beforeReverse = null; int index = 1; while (index != m) { beforeReverse = flag; flag = flag.next; index++; } ListNode node = flag; if (n == m) { return head; } else if (n - m == 1) { flag = flag.next; node.next = flag.next; flag.next = node; if (beforeReverse != null) { beforeReverse.next = flag; return head; } else { return flag; } } ListNode before = flag; flag = flag.next; ListNode after = flag.next; while (index != n) { flag.next = before; before = flag; flag = after; if (after != null) { after = after.next; } index++; } if (beforeReverse != null) { beforeReverse.next.next = flag; beforeReverse.next = before; return head; } else { node.next = flag; return before; } } }