实现单链表前后交叉排序:1,2,3,4,5,6 变成 1,4,2,5,3,6
通过改变指针的指向,进行数字位置的更改 如下图所示:
代码:
public class 单链表前后交叉 {
public static void main(String[] args) {
ListNode list = new ListNode();
list.addFirstNode(6);
list.addFirstNode(5);
list.addFirstNode(4);
list.addFirstNode(3);
list.addFirstNode(2);
list.addFirstNode(1);
System.out.println("没有前后交叉排序:");
list.displayAllNodes();
System.out.println("前后交叉排序后:");
int length = 6;
Change(list, length);
list.displayAllNodes();
}
public static void Change(ListNode list, int length){
int mid = length / 2;
ListNode cur = list.first; // mid以前的节点
ListNode another = list.first; // mid和mid以后的节点
int k = 0;
while(k < mid){
another = another.next;
k ++;
}
ListNode temp = another.next; // 临时变量
while(true){
another.next = cur.next;
cur.next = another;
if(temp == null){ // 判断是否到达尾部 否则会死循环
another.next = null;
break;
}
cur = another.next;
another = temp;
temp = temp.next;
}
}}
class ListNode{
public ListNode first; // 定义头结点
ListNode next;
int data;
public ListNode(){
}
public ListNode(int data){
this.data = data;
}
public void addFirstNode(int data) {
ListNode node = new ListNode(data);
node.next = first; // 将新增的节点指向之前的头结点
first = node; // 又将现在的node设置为头结点
}
public void displayAllNodes(){
ListNode current = first;
while (current != null){
current.show();
current = current.next;
}
System.out.println();
}
public void show(){
System.out.print(data+ "、");
}
}
样例演示如下: