每隔k次反转一次 链表_单链表每隔k个节点反转

public classLinkReverse2 {public static Node newLink(intn){

Node head= newNode();

head.setData(1);

head.setNext(null);

Node tmp=head;for(int i=2;i<=n;i++){

Node newNode= newNode();

newNode.setData(i);

newNode.setNext(null);

tmp.setNext(newNode);

tmp=newNode;

}returnhead;

}public static voidmain(String[] args) {

Node node= newLink(10);

pritNode(node);

Node node1= reverseKLink(node,3);

pritNode(node1);

}public static voidpritNode(Node head){

Node temp=head;while(temp !=null){

System.out.print(temp.getData()+"->");

temp=temp.getNext();

}

System.out.println();

}/*public static Node reverseLink(Node head){

Node pre=null,cur=head,next=null;

while(cur!=null){

next=cur.getNext();

cur.setNext(pre);

pre=cur;

cur=next;

}

return pre;

}*/

public static Node reverseKLink(Node head,intk){

Node pre=null,cur=head,next=null;

Node pnext=null,global_head=null;int i=0;

Node tmp=null;while(cur!=null){

next=cur.getNext();if(tmp==null) tmp=cur; //tmp记录当前组反转完最后一个节点

if(pnext!=null) pnext.setNext(cur); //pnext是上一组反转完最后一个节点

cur.setNext(pre);

pre=cur;

cur=next;

i++;if(i>=k){ //当前组反转完成的时候

if(global_head==null){

global_head=pre;

}if(pnext!=null){ //将上一组反转完的最后一个节点指向 当前组反转完后的第一个节点

pnext.setNext(pre);

}

pnext=tmp; //迭代

i=0; //新的一组反转时 关键数据初始化

tmp=null;

pre=null;

}

}returnglobal_head;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值