方案一(栈实现)
节点类
@Data
public class Node {
private Object data;
private Node next;
public Node(Object data) {
this.data = data;
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
}
实现类
public class Test03 {
public static void main(String[] args) {
Node lastNode = new Node(44);
Node node3 = new Node(33,lastNode);
Node node2 = new Node(22,node3);
Node headNode = new Node(11,node2);
reversePrint(headNode);
}
public static void reversePrint(Node headNode){
//处理headNode为null的情况
if (headNode == null)
throw new NullPointerException("headNode in null");
//创建一个栈
Stack stack = new Stack<>();
//遍历单链表中的所有节点
Node tempNode = headNode;
while (tempNode != null){
//把遍历出来的节点添加到栈中
stack.push(tempNode);
tempNode = tempNode.getNext();
}
//遍历栈中的所有节点
while (!stack.isEmpty()){
Node node = stack.pop();
System.out.print(node.getData()+" ");
}
}
}
方案二(递归实现)
public class Test04 {
public static void main(String[] args) {
//创建一个单链表
Node lastNode = new Node(44);
Node node3 = new Node(33,lastNode);
Node node2 = new Node(22,node3);
Node headNode = new Node(11,node2);
//从尾到头打印单链表(递归实现)
reversePrint(headNode);
}
public static void reversePrint(Node headNode){
//处理headNode为null的情况
if (headNode == null)
return;
//从尾到头打印以headNode下一个节点为首节点的链表
reversePrint(headNode.getNext());
//输出headNode中的数据值
System.out.print(headNode.getData() + " ");
}
}
递归过程解析