LintCode: Convert Array List to Linked List

Convert Array List to Linked List



Similar Problems:


Description

Convert an array list to a linked list.

Example

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

Github: code.dennyzhang.com

Credits To: lintcode.com

Leave me comments, if you have better ways to solve.


  • Solution: Without dummy Node
## Blog link: https://code.dennyzhang.com/convert-array-list-to-linked-list
## Basic Ideas:
## Complexity: Time O(n), Space O(n)
"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param: nums: an integer array
    @return: the first node of linked list
    """
    def toLinkedList(self, nums):
        if len(nums) == 0: return None
        res, p = None, None
        for num in nums:
            q = ListNode(num)
            if res is None:
                res, p = q, q
            else:
                p.next = q
                p = q
        return res

  • Solution: With dummy Node
## Blog link: https://code.dennyzhang.com/convert-array-list-to-linked-list
## Basic Ideas:
## Complexity: Time O(n), Space O(n)
"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param: nums: an integer array
    @return: the first node of linked list
    """
    def toLinkedList(self, nums):
        dummyNode = ListNode(None)
        p = dummyNode
        for num in nums:
            p.next = ListNode(num)
            p = p.next
        return dummyNode.next
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.