//类似冒泡,将第一个val一直冒泡到最后一位,以此类推
private static ListNode turnList(ListNode input) {
if(input == null) {
return null;
}
ListNode node = input;
ListNode now = input;
//获取链表长度
int length =0;
while(node!=null) {
length++;
node = node.next;
}
for(int i = 0;i<length;i++) {
node = input;
System.out.println("exchange time:"+(length-i));
//int val = node.value;
//这个地方用到了i,用i来控制要交换多少次,第一个要交换length-1次,第二个要交换length-2,第n个交换length-n
for(int j = 0;j<length-i-1;j++) {
if(node.next == null) {
break;
}
exchange(node,node.next);
PrintList(input);
node = node.next;
}
now = now.next;
}
return input;
}
private static void exchange(ListNode node, ListNode next) {
int val = node.value;
node.value = next.value;
next.value = val;
}