下面是一个步骤图,有这个图可以更好的理解整个过程。JAVA代码下后面贴上,一定要看过程图,否则不好理解。编写不易,请点个赞!
下面是代码
package main.sync;
public class Test18 {
public String val;
public Test18 next;
public Test18(String val){
this.val = val;
this.next = null;
}
public Test18(Test18 test){
this.val = "";
this.next = test;
}
public Test18(String val,Test18 test){
this.val = val;
this.next = test;
}
public static void main(String[] args){
Test18 a = new Test18("a");
Test18 b = new Test18("b");
Test18 c = new Test18("c");
Test18 d = new Test18("d");
Test18 e = new Test18("e");
Test18 f = new Test18("f");
Test18 g = new Test18("g");
Test18 h = new Test18("h");
Test18 i = new Test18("i");
Test18 j = new Test18("j");
Test18 k_ = new Test18("k");
a.next = b;
b.next = c;
c.next = d;
d.next = e;
e.next = f;
f.next = g;
g.next = h;
h.next = i;
i.next = j;
j.next = k_;
int k=3;
Test18 first = null;
Test18 cur = a,pre = null;
int num = 0;
int circle = 1;
Test18 tail = null,head=cur;
while (cur != null) {
Test18 tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
num++;
if(num==k){
if(circle%2!=0){
if(tail!=null){
tail.next = pre;
}
tail = cur;
if(circle==1){
first = pre;
}
}else{
head.next = pre;
head = cur;
}
circle++;
pre = null;
num = 0;
}
}
if(num!=0){//多余的反转回来
//掉头
cur = pre;
pre = null;
while(cur!=null){
Test18 tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
if(circle%2!=0){
if(tail!=null){
tail.next = pre;
}
}else{
head.next = pre;
}
}
System.out.println(first);
}
@Override
public String toString(){
Test18 now = this.next;
StringBuilder sb = new StringBuilder(val+"->");
while (now!=null){
sb.append(now.val).append("->");
now = now.next;
}
return sb.toString().substring(0,sb.length()-2);
}
}