题解 |链表指定区间翻转
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
思路
主要是分情况讨论,当m=1和m不等于1时,当m=1时,直接用头插法,不等于1时,找到翻转区间的前一个节点,再使用头插法。
代码
import java.util.*;
public class Solution {
public ListNode reverseBetween (ListNode head, int m, int n) {
if (m == 1){
ListNode tmp = head, p = head.next;
int index = 2;
while (index++ <= n){
tmp.next = p.next;
p.next = head;
head = p;
p = tmp.next;
}
return head;
}
// 遍历指针节点
ListNode p = head, pre = null;
int index = 1;
// 找到翻转区间的头结点
while (index++ < m){
pre = p;
p = p.next;
}
if (p == null) return head;
// 略过第一个节点
ListNode tmp = p;
p = p.next;
while (index++ <= n){
tmp.next = p.next;
p.next = pre.next;
pre.next = p;
p = tmp.next;
}
return head;
}
}