public class LinkReverse2 { public static Node mhead=null; public static Node mtail=null; public static Node newLink(int n){ Node head = new Node(); head.setData(1); head.setNext(null); Node tmp = head; for(int i=2;i<=n;i++){ Node newNode = new Node(); newNode.setData(i); newNode.setNext(null); tmp.setNext(newNode); tmp = newNode; } return head; } public static void main(String[] args) { Node node = newLink(10); pritNode(node); // Node node1 = reverseKLink(node,3); // Node node1 = reverse(node,2); Node node1 = reverseLink3(node,4); pritNode(node1); } public static void pritNode(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,int k){ 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; } } return global_head; }*/ //反转每组 public static void inreverse(Node left,Node right){ Node pre=null,cur=left,next=null; while(pre!=right){ next = cur.getNext(); cur.setNext(pre); pre=cur; cur=next; } if(mtail!=null) mtail.setNext(right); mhead=right; mtail=left; } //每k个节点为一组反转 public static Node reverseLink3(Node head,int k){ Node cur=head,global_head=head; int i=1; Node left=null,right=null; while(cur!=null){ if(i%k==1) left=cur; right=cur; cur=cur.getNext(); if(i%k==0){ inreverse(left,right); if(mtail!=null){ mtail.setNext(cur); } if(global_head==head){ global_head = mhead; } } i++; } return global_head; } }