链表一:从尾到头打印链表

/**
 * 题目:从尾到头打印链表
 * 描述:输入一个链表,从尾到头打印链表每个节点的值。
 * 解决方案:方法一:反转链表后进行遍历
 *        方法二:使用额外空间栈
 *        方法三:递归
 * */

public class One {

    //反转链表
    public static ListNode printfListTailtoHeadOne(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>(); //存放节点值

        ListNode head = listNode;    
        ListNode pre = null;//反转后的链表
        ListNode next = null;//中间过渡
        while(head !=null) {
            next = head.next; //得到链表下一个节点
            head.next = pre;//当前节点的下一个节点设置为上一个节点
            pre = head; //
            head = next;
        }
        while(pre !=null ) {
            list.add(pre.var);
            pre = pre.next;
        }
        return pre;
    }
    //额外使用空间栈
    public static ArrayList<Integer> printfListTailtoHeadTwo(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>();
        Stack<Integer> stack = new Stack<>();
        while(listNode != null) {
            stack.push(listNode.var);
            listNode = listNode.next;
        }
        while(!stack.empty()) {
            list.add(stack.pop());
        }
        return list;
    }
    //递归解法
  ArrayList<Integer> list = new ArrayList<>();
    public static ArrayList<Integer> printfListTailtoHeadThree(ListNode listNode) {
        if(listNode!=null) {
            if(listNode.next!=null) {
                printfListTailtoHeadThree(listNode.next);
            }
            list.add(listNode.var);
        }
        return list;
    }
    
    public static void main(String[] args) {
        

    }
    
    class ListNode{
        int var;
        ListNode next = null;
        ListNode(int var){
            this.var = var;
        }
    }
}
天助自助者
原文地址:https://www.cnblogs.com/ZeGod/p/9969314.html