package zuochengyun.chapter2;
public class ReverseList {
public static Node reverseList(Node head) {
Node pre=null;
Node next=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}
/
package zuochengyun.chapter2;
public class ReversePart {
public static Node myReversePart(Node head,int from,int to){
int len=0;
Node node1=head;
Node fpre=null;
Node tpos=null;
Node tend=null;
Node tstart=null;
//找出from的前一个节点和to的后一个节点
while(node1!=null){
len++;
fpre=len==(from-1)?node1:fpre;
tpos=len==(to+1)?node1:tpos;
tend=len==to?node1:tend;
tstart=len==from?node1:tstart;
node1=node1.next;
}
if(from>to||from<1||to>len){
return head;
}
tend.next=null;
//tend.next=tpos;
if(fpre!=null){
fpre.next=ReverseList.reverseList(tstart);
return head;
}
return tstart;
}
public static Node reversePart(Node head,int from,int to){
int len=0;
Node node1=head;
Node fpre=null;
Node tpos=null;
//找出from的前一个节点和to的后一个节点
while(node1!=null){
len++;
fpre=len==(from-1)?node1:fpre;
tpos=len==(to+1)?node1:tpos;
node1=node1.next;
}
if(from>to||from<1||to>len){
return head;
}
node1=fpre==null?head:fpre.next;//node1为要进行反转片段的头节点
Node node2=node1.next;//node2为对待反转片段进行反转时遍历的节点
node1.next=tpos;
Node next=null;
while(node2!=tpos){
next=node2.next;
node2.next=node1;
node1=node2;
node2=next;
}
if(fpre!=null){
fpre.next=node1;
return head;
}
return node1;
}
}