使用栈来实现
static class Node{
int data;
Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
@Override
public String toString() {
return "Node{" + "data=" + data + '}';
}
}
public static void main(String[] args) {
Node node3 = new Node(3, null);
Node node2 = new Node(2, node3);
Node node1 = new Node(1, node2);
print(node1);
}
private static void print(Node node) {
Node head = new Node(0, node);
Stack<Node> stack = new Stack<>();
while(head.next != null){
stack.push(head.next);
head = head.next;
}
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
}
使用递归来实现
static class Node{
int data;
Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
@Override
public String toString() {
return "Node{" + "data=" + data + '}';
}
}
public static void main(String[] args) {
Node node3 = new Node(3, null);
Node node2 = new Node(2, node3);
Node node1 = new Node(1, node2);
print(node1);
}
private static void print(Node node) {
if(node == null){
return ;
}
if(node.next != null){
print(node.next);
}
System.out.println(node);
}