09:逆序打印一個鏈表

逆序打印一個鏈表

用一個棧結構或者一個數組可以,只要保證“先進後出”的準則即可

public class Offer09 {
   public static void main(String[] args) {
       Node node1 = new Node(1);
       Node node2 = new Node(2);
       Node node3 = new Node(3);
       Node node4 = new Node(4);
       Node node5 = new Node(5,null);
       node1.setNext(node2);
       node2.setNext(node3);
       node3.setNext(node4);
       node4.setNext(node5);

       printList(node1);
   }

   public static void printList(Node node){
       Stack<Integer> stack = new Stack<>();
       while (node!=null){
           stack.push(node.getValue());
           node = node.getNext();
       }
       while (!stack.empty()){
           Integer pop = stack.pop();
           System.out.println(pop);
       }
   }

}
class Node{
   private Integer value;
   private Node next;

   public Node(Integer value) {
       this.value = value;
   }

   public Node(Integer value, Node next) {
       this.value = value;
       this.next = next;
   }

  //getter.setter
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章