从尾到头打印链表

利用stack的性质

    public static class ListNode {  
        int val; // 结点的值 
        ListNode nxt; // 下一个结点 
    }

    public static void printListInverselyUsingIteration(ListNode root) {  
        Stack<ListNode> stack = new Stack<>();  
        while (root != null) {  
            stack.push(root);  
            root = root.nxt;  
        }  
        ListNode tmp;  
        while (!stack.isEmpty()) {  
            tmp = stack.pop();  
            System.out.print(tmp.val + " ");  
        }  
    }

    public static void printListInverselyUsingRecursion(ListNode root) {  
        if (root != null) {  
            if(root.nxt!=null)
                printListInverselyUsingRecursion(root.nxt);  
                System.out.print(root.val + " ");  
            }
        }  
    }  

你可能感兴趣的:(从尾到头打印链表)