Convert a linked list to an array list.
将一个链表转换为一个数组。
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;
}
}
原文:https://www.cnblogs.com/browselife/p/10646003.html