剑指offer——第三题

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

/**
 * 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
 */
class Node {
    int val;
    Node next;

    public Node(int val) {
        this.val = val;
    }
}
public class o_3 {

    //方法一:非递归
    public ArrayList<Integer> printListFromTailToHead(Node node) {

        Stack<Integer> stack = new Stack<>();
        while (node != null) {
            stack.push(node.val);
            node = node.next;
        }

        ArrayList<Integer> list = new ArrayList<>();
        while (!stack.isEmpty()) {
            list.add(stack.pop());
        }
        return list;
    }

//    方法二:递归实现
//    ArrayList<Integer> arrayList=new ArrayList<Integer>();
//    public ArrayList<Integer> printListFromTailToHead(Node node) {
//
//        if(node!=null){
//            this.printListFromTailToHead(node.next);
//            arrayList.add(node.val);
//        }
//        return arrayList;
//    }

    public static void main(String[] args) {
        o_3 o3 = new o_3();

        Node node1 = new Node(123);
        Node node2 = new Node(456);
        Node node3 = new Node(789);

        node1.next = node2;
        node2.next = node3;

        ArrayList<Integer> result = o3.printListFromTailToHead(node1); //结果:[789, 456, 123]
        //ArrayList<Integer> result = o3.printListFromTailToHead(node2); //结果:[789, 456]
        //ArrayList<Integer> result = o3.printListFromTailToHead(node3); //结果:[789]

        System.out.println(result);
    }
}

猜你喜欢

转载自blog.csdn.net/dl674756321/article/details/89737661