【题目】输入一个链表的头节点,从尾到头反过来打印每个节点的值。
1. 遍历的顺序是从头到尾,打印的顺序则是从尾到头,首先,想到栈,然后,递归的本质是一个栈结构,因此,想到用递归。
1 import java.util.Stack; 2 3 public class Main { 4 5 Stack<Node> stack = new Stack<Node>(); 6 7 public static void main(String[] args) { 8 9 Node node4 = new Node(4, null); 10 Node node3 = new Node(3, node4); 11 Node node2 = new Node(2, node3); 12 Node node1 = new Node(1, node2); 13 Node node0 = new Node(0, node1); 14 15 Main main = new Main(); 16 17 main.process(node0); 18 main.process2(node0); 19 20 } 21 22 // 递归实现 23 public void process(Node head) { 24 25 if (null != head) { 26 27 if (null != head.next) { 28 process(head.next); 29 } 30 31 System.out.print(head.value + " "); 32 } 33 } 34 35 // 栈实现 36 public void process2(Node head) { 37 38 Node p = head; 39 40 while (null != p) { 41 stack.add(p); 42 p = p.next; 43 } 44 45 while (!stack.isEmpty()) { 46 System.out.print(stack.pop().value + " "); 47 } 48 } 49 } 50 51 class Node { 52 int value; 53 Node next; 54 55 public Node(int value, Node nextNode) { 56 this.value = value; 57 this.next = nextNode; 58 } 59 }