LintCode: Convert Linked List to Array List

Convert Linked List to Array List



Similar Problems:


Description

Convert a linked list to an array list.

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

Github: code.dennyzhang.com

Credits To: lintcode.com

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


  • Solution:
// Blog link: https://code.dennyzhang.com/convert-linked-list-to-array-list
// Basic Ideas: One pass
// Complexity: Time O(n), Space O(n)
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

/**
 * @param head: the head of linked list.
 * @return: An integer list
 */
func toArrayList (head *ListNode) []int {
    res := []int{}
    p := head
    for p != nil {
        res = append(res, p.Val)
        p = p.Next
    }
    return res
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.