Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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()
share|improve this question
    
Use Python 3.4 @singledispatch. –  Morwenn Apr 1 '14 at 8:36

1 Answer 1

up vote 5 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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