题解 | #链表内指定区间反转#
链表内指定区间反转
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
if(head == null){
return null;
}
if(head.next==null || m==n){
return head;
}
ListNode startNode1 = null;
ListNode startNode2 = null;
ListNode endNode1 = null;
ListNode endNode2 = null;
ListNode copyHead = head;
ListNode copyHead2 = head;
if(m==1){
startNode1=startNode2 = head;
for(int i=1;i<n;i++){
head = head.next;
}
endNode1 = head;
endNode2 = head.next;
endNode1.next = null;
ListNode reverseList=null;
reverseList = ReverseList(startNode1);
copyHead = reverseList;
while(reverseList.next!=null){
reverseList = reverseList.next;
}
reverseList.next = endNode2;
return copyHead;
}else{
for(int i=1;i<m-1;i++){
head = head.next;
}
startNode1 = head;
startNode2 = head.next;
startNode1.next=null;
head = startNode2;
for(int i=m;i<n;i++){
head = head.next;
}
endNode1 = head;
endNode2 = head.next;
endNode1.next = null;
ListNode reverseList=null;
reverseList=ReverseList(startNode2);
ListNode end = reverseList;
while(end.next!=null){
end = end.next;
}
startNode1.next=reverseList;
end.next = endNode2;
return copyHead;
}
}
public ListNode ReverseList(ListNode head) {
if(head==null){
return null;
}
ListNode currentNode = null;
ListNode temp = null;
ListNode endNode = null;
if(head.next==null){
return head;
}else{
currentNode = head.next;
head.next = null;
endNode = head;
}
while(currentNode!=null){
temp = currentNode.next;
currentNode.next = head;
head = currentNode;
currentNode = temp;
}
return head;
}
}