题解 | #链表内指定区间反转# 先创建头结点,然后保存前节点、当前节点以及下一节点进行反转
链表内指定区间反转
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) {
int count = m;
ListNode tmp = head;
ListNode preNode = new ListNode(-1);
preNode.next = tmp;
ListNode retHeadNode = preNode;
ListNode nextNode;
ListNode next2Node;
while(m != 1){
preNode = tmp;
tmp = tmp.next;
m--;
}
while(tmp != null && count < n){
nextNode = tmp.next;
next2Node = tmp.next.next;
ListNode nextTmpNode = preNode.next;
preNode.next = nextNode;
nextNode.next = nextTmpNode;
tmp.next = next2Node;
count++;
}
return retHeadNode.next;
}
}
/*
* 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) {
int count = m;
ListNode tmp = head;
ListNode preNode = new ListNode(-1);
preNode.next = tmp;
ListNode retHeadNode = preNode;
ListNode nextNode;
ListNode next2Node;
while(m != 1){
preNode = tmp;
tmp = tmp.next;
m--;
}
while(tmp != null && count < n){
nextNode = tmp.next;
next2Node = tmp.next.next;
ListNode nextTmpNode = preNode.next;
preNode.next = nextNode;
nextNode.next = nextTmpNode;
tmp.next = next2Node;
count++;
}
return retHeadNode.next;
}
}