剑指offer(Java版)第四题:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。

/*
输入一个链表的头结点,从尾到头反过来打印出每个结点的值。结点定义如下:
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}
*/
//题目符合后进先出,类似的数据结构有栈,也可以使用递归

import java.util.*;

public class Class5 {

static class ListNode{
int val;
ListNode next = null;
ListNode(int val){
this.val = val;
}
}
//使用栈
static class reversePrint_method1{
public void reversePrint_method1(ListNode a){
Stack<ListNode> stack = new Stack<ListNode>();
while(a != null){
stack.push(a);
a = a.next;
}
while(!stack.empty()){
System.out.println(stack.pop().val);
}
}
}
//使用递归
static class reversePrint_method2{
public void reversePrint_method2(ListNode a){
if(a != null){
reversePrint_method2(a.next);
System.out.println(a.val);
}
}
}

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("设置一个链表");
ListNode listNode1 = new ListNode(1);
ListNode listNode2 = new ListNode(2);
ListNode listNode3 = new ListNode(3);
listNode1.next = listNode2;
listNode2.next = listNode3;
System.out.println("使用栈:");
reversePrint_method1 rpm1 = new reversePrint_method1();
rpm1.reversePrint_method1(listNode1);
System.out.println("使用递归:");
reversePrint_method1 rpm2 = new reversePrint_method1();
rpm2.reversePrint_method1(listNode1);
}

}

原文地址:https://www.cnblogs.com/zhuozige/p/12371854.html