-
Notifications
You must be signed in to change notification settings - Fork 0
/
Convert Array List to Linked List.java
49 lines (48 loc) · 1.14 KB
/
Convert Array List to Linked List.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
Convert an array list to a linked list.
Example
Given [1,2,3,4], return 1->2->3->4->null.
*/
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param nums an integer array list
* @return the first node of linked list
*/
public ListNode toLinkedList(ArrayList<Integer> nums) {
// Write your code here
if(nums.size()==0){
return null;
}
ListNode head=null, p=null;
// for(int i=0;i<nums.size(); i++){
// if(head==null){
// head=new ListNode(nums.get(i));
// p=head;
// }else{
// p.next=new ListNode(nums.get(i));
// p=p.next;
// }
// }
for(int item: nums){
if(head==null){
head=new ListNode(item);
p=head;
}else{
p.next=new ListNode(item);
p=p.next;
}
}
return head;
}
}