相反的顺序存储

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Primary_wind/article/details/80457192

题目

相反的顺序存储
给出一个链表,并将链表的值以in reverse order存储到数组中。

样例
给定1 -> 2 -> 3 -> null,返回[3,2,1]。

解答

public class FanZhuanList {
    /**
     * @param head: the given linked list
     * @return: the array that store the values in reverse order
     */
    public List<Integer> reverseStore(ListNode head) {
        // write your code here

        List<Integer> result = new ArrayList<Integer>();
        List<Integer> originResult = new ArrayList<Integer>();
        while (head != null) {
            originResult.add(head.val);
            head = head.next;
        }

        for (int i = originResult.size() - 1; i >= 0; i--) {
            result.add(originResult.get(i));
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/Primary_wind/article/details/80457192
今日推荐