链表前后续递归遍历
思路:先创建一个长度为10的数组并初始化,用尾插法插入空链表(即正序),然后分别创建前序递归遍历方法和后续递归遍历方法,进行实现并与原链表数值进行对比。
前序递归遍历:
public void FormerSequenceTraversal(Node head){
//前续递归遍历,先打印后移动 Iterate recursively before printing and then moving
head = head.next;
if(head != null){
System.out.print(head.data + " ");
FormerSequenceTraversal(head);
}else{
return;
}
}
后续递归遍历:
public void ReverseTraversal(Node head){
//后续递归遍历,先移动后打印,移动到末尾,向前依次返回值
//The following recursive traversal, first move, then print, move to the end, return the value in turn forward
head = head.next;
if(head != null){
ReverseTraversal(head);
System.out.print(head.data + " ");
}else{
return;
}
}
总代码:
import java.util.Random;
//创建节点类 Creating a node class
class Node<E> {
E data;
Node<E> next;
public Node(E data){
this.data = data;
this.next = null;
}
}
public class Linklist_recursion<E> {
Node<E> head;
//构造方法,将每个节点的next初始化为null Constructor to initialize next to null for each node
public Linklist_recursion(){
head = new Node(null);
}
//尾插法
public void TailPlug(Node head,E[] arr){
Node<E> tail;
Node<E> node;
tail = head;
for(int curpos=0;curpos < arr.length;curpos ++){
node = new Node<>(arr[curpos]);
tail.next = node;
tail = node;
}
}
//打印链表方法 Print list method
public void Print(Node head){
head = head.next;
while(head != null){
System.out.print(head.data + " ");
head = head.next;
}
}
//前序遍历方法 Preorder traversal method
public void FormerSequenceTraversal(Node head){
//前续递归遍历,先打印后移动 Iterate recursively before printing and then moving
head = head.next;
if(head != null){
System.out.print(head.data + " ");
FormerSequenceTraversal(head);
}else{
return;
}
}
//后序遍历方法 Post-order traversal method
public void ReverseTraversal(Node head){
//后续递归遍历,先移动后打印,移动到末尾,向前依次返回值
//The following recursive traversal, first move, then print, move to the end, return the value in turn forward
head = head.next;
if(head != null){
ReverseTraversal(head);
System.out.print(head.data + " ");
}else{
return;
}
}
public static void main(String[] args) {
//创建一个长度为10的数组arr Create an array arr of length 10
Integer[] arr = new Integer[10];
Random random = new Random();
System.out.println("原数组:");
//用随机数初始化数组arr Initialize array arr with random numbers
for(int curpos=0;curpos < arr.length;curpos ++){
arr[curpos] = random.nextInt(100);
System.out.print(arr[curpos] + " ");
}
System.out.println();
Linklist_recursion linklist = new Linklist_recursion();
//用尾插法将数组挨个插入链表linklist中 Insert arrays into Linklist one by one using tail insertion
linklist.TailPlug(linklist.head,arr);
System.out.println("尾插法插入链表linklist:");
linklist.Print(linklist.head);
System.out.println();
System.out.println("前序递归遍历:");
linklist.FormerSequenceTraversal(linklist.head);
System.out.println();
System.out.println("后序递归遍历:");
linklist.ReverseTraversal(linklist.head);
}
}
代码结果:
原数组:
68 85 55 9 4 5 40 14 75 65
尾插法插入链表linklist:
68 85 55 9 4 5 40 14 75 65
前序递归遍历:
68 85 55 9 4 5 40 14 75 65
后序递归遍历:
65 75 14 40 5 4 9 55 85 68