首页 > 代码库 > java实现——005从尾到头打印链表

java实现——005从尾到头打印链表

 1 import java.util.Stack;
 2 public class T005 {
 3     public static void main(String[] args){
 4         Node n1 = new Node(1);
 5         Node n2 = new Node(2);
 6         Node n3 = new Node(3);
 7         Node n4 = new Node(4);
 8         Node n5 = new Node(5);
 9         n1.next = n2;
10         n2.next = n3;
11         n3.next = n4;
12         n4.next = n5;
13         reversePrint(n1);
14     }
15     public static void reversePrint(Node head){
16         
17         Stack s = new Stack();
18         while(head!=null){
19             s.push(head.val);
20             head = head.next;
21         }    
22         while(!s.empty()){
23             
24             System.out.println(s.lastElement());
25             s.pop();
26         }
27     }
28     public static class Node{
29         int val;
30         Node next;
31         public Node(int val){
32             this.val = val;
33         }
34     }
35 }