题解 | #链表内指定区间反转#
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
public ListNode reverseBetween (ListNode head, int m, int n) {
ListNode res = new ListNode(0);
res.next = head;
ListNode node = res;
//获得翻转节点的前一位,为了后面拼接反转后的节点
ListNode before = res;
int i = 0;
while (i < m) {
before = node;
node = node.next;
i++;
}
//获得第一个翻转节点,后面一直交换位置,直到执行null或者n+1位不需要翻转的节点
ListNode cur = before.next;
ListNode next = null;
while (i < n) {
next = cur.next;
cur.next = next.next;
next.next = before.next;
before.next = next;
i++;
}
return res.next;
}
}