对链表进行反转(部分反转)



public class Linked {
public static void main(String[] args) {
LNode n1 = new LNode(1);
LNode n2 = new LNode(2);
LNode n3 = new LNode(3);
LNode n4 = new LNode(4);
LNode n5 = new LNode(5);
LNode n6 = new LNode(6);
LNode n7 = new LNode(7);
// LNode n8 = new LNode(8);


n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
n6.next = n7;
// n7.next =n8;


int len = fromTo(n1);
int temp = len % 2 ;
int from = temp== 0? (len+2)/2 : (len+1)/2;
System.out.println(from+"::"+len);
System.out.println("当前列表为:");
print(n1);
System.out.println("部分反转后的列表为:");
LNode n = reversePart(n1,from,len);
print(n);
}
public static int fromTo(LNode head){
LNode cur = head;
int count = 0;
while(cur != null){
count++;
cur=cur.next;

}
return count; 
}
public static LNode reversePart(LNode head,int from,int to){
LNode node1 = head;
LNode fPre = null;
LNode tPos = null;
int len = 0;

while(node1 != null){
len++;
fPre = len == from - 1 ? node1 : fPre;
tPos = len == to + 1 ? node1 : tPos;
node1 = node1.next;
}
System.out.println("fpre=");
print(fPre);
System.out.println();

if(from > to || from < 1 || to > len)
return head;
node1 = fPre == null ? head : fPre.next;
LNode node2 = node1.next;
node1.next = tPos;
LNode 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;
}
private static void print(LNode l) {
LNode ll=l;
while(ll!=null){
System.out.print(ll.value);
ll=ll.next;
}

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值