5
\$\begingroup\$

I've created a linked list class in Python, but I'm not sure how to enforce only passing Node objects into the insert routine.

# linked list in Python

class Node:
    """linked list node"""
    def __init__(self, data):
        self.next = None
        self.data = data
    def insert(self, n):
        n.next = self.next
        self.next = n
        return n
    def showall(self):
        print self.data
        if self.next != None:
            self.next.showall()


ll = Node("one")
ll.insert(Node("two")).insert(Node("three"))
ll.showall()
\$\endgroup\$
1
  • \$\begingroup\$ Use Python 3.4 @singledispatch. \$\endgroup\$
    – Morwenn
    Apr 1 '14 at 8:36
5
\$\begingroup\$

You could delegate the construction of nodes to the insert function :

#!/usr/bin/python

# linked list in Python

class Node:
    """linked list node"""
    def __init__(self, data):
        self.next = None
        self.data = data
    def insert(self, data):
        n = Node(data)
        n.next = self.next
        self.next = n
        return n
    def showall(self):
        print self.data
        if self.next != None:
            self.next.showall()


ll = Node("one")
ll.insert("two").insert("three")
ll.showall()

You could make this more concise by adding a default argument to your __init__() :

class Node:
    """linked list node"""
    def __init__(self, data, next=None):
        self.next = next
        self.data = data
    def insert(self, data):
        self.next = Node(data, self.next)
        return self.next
    def showall(self):
        print self.data
        if self.next != None:
            self.next.showall()


ll = Node("one")
ll.insert("two").insert("three")
ll.showall()

Additional point : from PEP 8 :

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.