483.链表转数组

Convert Linked List to Array List

Description

Convert a linked list to an array list.
将一个链表转换为一个数组。

Example

Given 1->2->3->null, return [1,2,3].

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: the head of linked list.
     * @return: An integer list
     */
    public List<Integer> toArrayList(ListNode head) {
        // write your code here
        // List<Integer> res = new ArrayList<Integer>();
        // if(head != null){
        //     for(int i=head.val; i>0; i--){
        //         res.add(i);
        //     }
        // }
        // return res;
        List<Integer> res = new ArrayList<Integer>();
        while(head != null){
            res.add(head.val);
            head = head.next;
        }
        return res;
    }
}

posted @ 2019-04-02 22:48  故人叹  阅读(436)  评论(0编辑  收藏  举报