我用String代替了链表显示,本题的大意是每k个进行逆序处理,剩下的不够k个的就按照原顺序保留下来。
public class ReverseNodes {
public static void main(String[] args) {
String str = "1->2->3->4->5->6->7->8->9->10->11->12->13->14->15";
String[] strArray = str.split("->");
int k = 2;
/**
* int k = 2; 2->1->4->3->6->5->8->7->10->9->12->11->14->13->15
* int k = 4; 4->3->2->1->8->7->6->5->12->11->10->9->13->14->15
* int k = 3; 3->2->1->6->5->4->9->8->7->12->11->10->15->14->13
*/
String[] results = reveseNodes(k,strArray);
for(int i = 0; i < results.length; ++i){
if(i == strArray.length - 1){
System.out.print(results[i]);
}else{
System.out.print(results[i] + "->");
}
}
}
public static String[] reveseNodes(int k, String[] strArray) {
int left = strArray.length % k;
int start = 0;
if(strArray.length / k == 0){
return strArray;
}
while(start < strArray.length - left){
DiedaiReverse(start,k,strArray);
start += k;
}
return strArray;
}
public static void DiedaiReverse(int start, int k, String[] strArray) {
int j = 0;
if(k%2 == 0){
for(int i = start; i < (start + start + k)/2; ++i){
String temp = strArray[i];
strArray[i] = strArray[start+k-1-j];
strArray[start+k-1-j] = temp;
++j;
}
}else{
for(int i = start; i <= (start + start + k)/2; ++i){
String temp = strArray[i];
strArray[i] = strArray[start+k-1-j];
strArray[start+k-1-j] = temp;
++j;
}
}
}
}