Lintcode489-Convert Array List to Linked List-Easy

489. Convert Array List to Linked List

Convert an array list to a linked list.

Example

Example 1:

Input: [1,2,3,4], 
Output: 1->2->3->4->null

  

 定义两空指针,一个用来返回整个链表,一个用来创建新节点。 新创建的节点作为当前p的next节点,再把p重新指向新创建的节点。

public ListNode toLinkedList(List<Integer> nums) {
    if (nums.size() == 0) {
        return null;
    }
    ListNode head = null;
    ListNode p = null;
    for (Integer num : nums) {
        // 创建头节点
        if (head == null) {
            head = new ListNode(num);
            p = head;
        } else {
            p.next = new ListNode(num);
            p = p.next;
        }
    }
    return head;

 

posted @ 2019-04-22 09:49  IreneZh  阅读(158)  评论(0编辑  收藏  举报