从尾到头打印链表

输入一个链表,从尾到头打印链表每个节点的值。 

输入描述:
输入为链表的表头
输出描述:
输出为需要打印的“新链表”的表头
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>();
        if(listNode == null) return list;
        ListNode current = listNode;
        ListNode temp = null;
        ListNode next = null;
        while(current!=null){
            next = current.next;
            current.next = temp;
            temp = current;
            current = next;
        }
        while(temp!=null){
            list.add(temp.val);
            temp = temp.next;
        }
        return list;
    }

思路2:把节点存入到栈中,输出栈中的元素即可。

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack = new Stack<>();
        ArrayList<Integer> arrayList = new ArrayList<>();
        if(listNode == null) return arrayList;
        while(listNode!=null){
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        while(!stack.isEmpty()){
            arrayList.add(stack.pop());
        }
        return arrayList;
    }
原文地址:https://www.cnblogs.com/yingpu/p/5830348.html