Converting a list to a linked list

I'm trying to figure out to convert a list to a linked list. I already have a class for the link but I'm trying to figure out how to convert a list to linked list, for example:

def list_to_link(lst):
    """Takes a Python list and returns a Link with the same elements.

    >>> link = list_to_link([1, 2, 3])
    >>> print_link(link)
    <1 2 3>
    """


class Link:

    empty = ()

    def __init__(self, first, rest=empty):
        assert rest is Link.empty or isinstance(rest, Link)
        self.first = first
        self.rest = rest

def print_link(link):
    """Print elements of a linked list link."""

    >>> link = Link(1, Link(2, Link(3)))
    >>> print_link(link)
    <1 2 3>
    >>> link1 = Link(1, Link(Link(2), Link(3)))
    >>> print_link(link1)
    <1 <2> 3>
    >>> link1 = Link(3, Link(Link(4), Link(5, Link(6))))
    >>> print_link(link1)
    <3 <4> 5 6>
    """
    print('<' +helper(link).rstrip() +'>')

Matt's answer is good, but it's outside the constraint of the function prototype described in the problem above.

Reading the abstract/prototype, it looks like the creator of the problem wanted to solve this with recursive/dynamic programming methodology. This is a pretty standard recursive algorithm introduction. It's more about understanding how to write elegant recursive code more than creating linked-list in Python (not really useful or common).

Here's a solution I came up with. Try it out:

class Link:
    empty = ()

    def __init__(self, first, rest=empty):
        assert rest is Link.empty or isinstance(rest, Link)
        self.first = first
        self.rest = rest


def print_link(link):
    """Print elements of a linked list link.
    """
    print('<' + helper(link).rstrip() +'>')


def list_to_link(lst):
    """Takes a Python list and returns a Link with the same elements.
    """
    if len(lst) == 1:
        return Link(lst[0])
    return Link(lst[0], list_to_link(lst[1:]))  # <<<< RECURSIVE

def helper(link):
    if isinstance(link.first, Link):
        first = '<' + helper(link.first).rstrip() + '>'  # <<<< RECURSIVE
    else:
        first = str(link.first)

    if link.rest != Link.empty:
        return first + ' ' + helper(link.rest)  # <<<< RECURSIVE
    else:
        return first + ' '

def main():
    """ Below are taken from sample in function prototype comments
    """
    link = list_to_link([1, 2, 3])
    print_link(link)

    link = Link(1, Link(2, Link(3)))
    print_link(link)
    link1 = Link(1, Link(Link(2), Link(3)))
    print_link(link1)
    link1 = Link(3, Link(Link(4), Link(5, Link(6))))
    print_link(link1)


if __name__ == '__main__':
    main()

Create linked list from a given array, Matt's answer is good, but it's outside the constraint of the function prototype described in the problem above. Reading the abstract/prototype,� The above singly linked list is converted into circular linked list. Recommended: Please try your approach on {IDE} first, before moving on to the solution. Approach: The idea is to traverse the singly linked list and check if the node is the last node or not.

This is what you want.

class Node(object):
    def __init__(self, value, next=None):
        self.value = value
        self.reference = next

class LinkedList(object):
    def __init__(self, sequence):
        self.head = Node(sequence[0])
        current = self.head
        for item in sequence[1:]:
            current.reference = Node(item)
            current = current.reference
a = range(10)
li = LinkedList(li)
current = li.head
while current is not None:
    print current.value
    current = current.reference

Converting a list to a linked list, A list and a linked list often look exactly the same, but how can I convert a list to a liked list? if I have [8,0,5] how do I convert it to [8,0,5] (8 -> 0� Given a multilevel linked list, convert it into a singly linked list in such a way that all nodes of first level appears first, followed by all nodes of second level, and so on. The multilevel linked list is similar to the simple linked list except that it has one extra field which points to the child of that node.

I have an idea using dummy ListNode. This makes code simple and neat.

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


def lst2link(lst):
    cur = dummy = ListNode(0)
    for e in lst:
        cur.next = ListNode(e)
        cur = cur.next
    return dummy.next

How to convert list to linked list?, A linked list contains a node with a next pointer pointing to the next node. Let's create a simple class for our Linked List [code]class LinkedList: def __init__(self, � Approach: An approach to create a linked list from the given array has been discussed in this article. Here, an approach to convert the given linked list to an array will be discussed.

How to convert a list into a linked list using Python, Description Program to add all the elements of a List to the LinkedList using addAll() method of LinkedList class. Example import java.util.ArrayList; Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.

Append all the elements of a List to LinkedList, Example In this example we are converting a LinkedList to ArrayList. We have a List; public class ConvertExample { public static void main(String[] args)� In the above example, we have created a linked list named languages. Notice the line, languages.toArray(arr); Here, the toArray() method converts the linked list languages into an array. And stores it in the string array arr.

Java - Convert a LinkedList to ArrayList, The resultant LinkedList should contain all elements of the ArrayList. We know that ArrayList is resizable-array implementation and LinkedList is Doubly-linked list� Create a sorted linked list from the given Binary Tree; Count rotations in sorted and rotated linked list; Check if linked list is sorted (Iterative and Recursive) Remove duplicates from a sorted linked list using recursion; Remove all occurrences of duplicates from a sorted Linked List; Sort linked list which is already sorted on absolute values

Comments
  • Why do you need a linked-list? What kind of functionality would it offer? (not already offered by std lists)
  • Its simply an exercise for an assignment. I'm guessing they want us to think about linked lists as a mutable function but I'm confused on how to approach the question.
  • This could be helpful interactivepython.org/runestone/static/pythonds/BasicDS/…
  • thanks! I'll take a look
  • I don't think this is quite the same as a linked list. You have nested all of the Links into a single Link.
  • Alright thanks, I havent learned about Nodes yet so I dont really understand the code but thanks for your input!
  • @d'chang The Node is a container with a value and a pointer to the next node aka the reference. Try running the code and you'll see that it converts a Python list into a LinkedList. It seems like you changed your question though.
  • oh yeah sorry @Matt. I did. I figured out how the previous question I'm sorry if that wasn't clear. I will change it back to accommodate your answer