题解 | #链表内指定区间反转#
链表内指定区间反转
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) {
// write code here
ListNode pre = new ListNode(0);
pre.next = head;
//找到第一个节点的前一个节点
ListNode f0 = pre;
for(int i = 0; i < m - 1; i++){
f0 = f0.next;
}
//找到第二个节点的当前节点
ListNode f2 = pre;
for(int i = 0; i < n ; i++){
f2 = f2.next;
}
//第一个节点
ListNode f1 = f0.next;
//第二个节点的下一个节点
ListNode f3 = f2.next;
//断开链表
f0.next = null;
f2.next = null;
//反转
reverse(f1);
//拼接
f0.next = f2;
f1.next = f3;
return pre.next;
}
public ListNode reverse(ListNode head){
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}