题目地址:
https://www.lintcode.com/problem/convert-array-list-to-linked-list/description
给定一个数组,将其转化为一个单链表。
import java.util.List;
public class Solution {
/*
* @param nums: an integer array
* @return: the first node of linked list
*/
public ListNode toLinkedList(List<Integer> nums) {
// write your code here
if (nums == null || nums.size() == 0) {
return null;
}
ListNode dummy = new ListNode(0), prev = dummy;
for (int num : nums) {
prev.next = new ListNode(num);
prev = prev.next;
}
return dummy.next;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。