// 创建一个任意数目的单项链表,每项的位置作为自己的初始数据
// 返回链头
Node initLink(int num){
Node head = new Node();
head.data = 1;
Node temp1 = head;
for(int i = 2; i<=num; i++){
// 创建第二个
Node temp2 = new Node();
temp2.data = i;
// 第一个指向第二个
temp1.next = temp2;
// 把第二个作为下一轮的第一个
temp1 = temp2;
}
return head;
}
// 输出单项链表的全部数据
void display(Node head){
if(head == null){
System.out.println("No any nodes!");
}
Node curNode = head;
while(curNode.next != null){
System.out.println(curNode.data);
curNode = curNode.next;
}
System.out.println(curNode.data);
}
// 倒叙链表,返回新的链头
Node reverseLink(Node head){
// 存起第一个
Node temp1 = head;
// 存起第二个
Node temp2 = head.next;
// 第一个前面清空,作为尾
temp1.next = null;
while(temp2.next != null){
// 存起第三个
Node temp3 = temp2.next;
// 第二个指向第一个
temp2.next = temp1;
// 第二个作为下一轮第一个
temp1 = temp2;
// 第三个作为下一轮第二个
temp2 = temp3;
}
temp2.next = temp1;
// 最尾的作为头,返回新的头
return temp2;
}
// 测试代码
public static void main(String[] args) {
Node head = initLink(10);
System.out.println("Step1");
display(head);
head = reverseLink(head);
System.out.println("Step2");
display(head);
System.out.println("Finish");
}
最后的输出:
Step1
1
2
3
4
5
6
7
8
9
10
Step2
10
9
8
7
6
5
4
3
2
1
Finish