Alfons
Alfons

Reputation: 15

Doubly-linked list implementation not working

I'm new to object-orientated programming and to this site.

I've been working on this program for a university-project for quite a while (or at least I'm trying to). I have to create a program that deals with doubly-linked lists, to be more precise, I need to implement the following things:

This is what my code looks like so far:

class Node:
    def __init__(self):
        self.value = None
        self.next_node = None
        self.previous_node = None

class LinkedList(object):
    def __init__(self):
        self.first = None
        self.last = None

    def __str__(self):
        return 'This is the value: '.format(self.first)

    def append(self, value):
        new_node = Node()
        self.first = new_node

def main():
    myList = LinkedList()
    myList.append(20)
    print(myList)

I'd expect the output to be: "This is the value: 20".

But the output I get is: "This is the value: ".

What is my mistake? Either my append method or my __str__ method don't work correctly (or neither do). (It's probably something really obvious)

Upvotes: 0

Views: 306

Answers (1)

Craig
Craig

Reputation: 4855

Add {} to the string to tell format where to put the value.

def __str__(self):
    return 'This is the value: {}'.format(self.first)

See the Python docs for string format examples.

And, per @Jeremy's comment, you also need to assign the value to the new Node and add a str() function to the Node class.

This should work:

class Node:
    def __init__(self, value=None):
        self.value = value # <- store the value in the object
        self.next_node = None
        self.previous_node = None

    def __str__(self):             # <- return the value as a string
        return str(self.value)

class LinkedList(object):
    def __init__(self):
        self.first = None
        self.last = None

    def __str__(self):
        return 'This is the value: {}'.format(self.first)

    def append(self, value):
        new_node = Node(value) # <- pass value to the Node
        self.first = new_node
main()
    myList = LinkedList()
    myList.append(20)
    print(myList)

Upvotes: 2

Related Questions