greenslime
greenslime

Reputation: 11

Printing a node in a linked list

I'm very new to coding and I have a basic question about printing a node in a doubly linked list in Python.

class Node():
    def __init__(self, key = None, prev = None, next = None):
        self.key = key
        self.prev = prev
        self.next = next

    def __str__(self):
        return ('[%s][%d][%s]' % (repr(self.prev), self.key, repr(self.next)))

Obviously I then have some more code for the list class itself. Let's say I have a doubly linked list with two nodes:

node1: key 21
node2: key 10
head --> node1 <==> node2

If I do print(node1) I get:

[*location of prev node*][21][*location of next node*]

which works exactly how I want.

So 2 questions:

  1. Is this code "messy" or acceptable syntax for the str method?

  2. Instead of printing the location of the prev and next nodes, how would I print the names of the nodes instead e.g. [node7][82][node9]?

Hope this makes sense, and thanks for any help!

Upvotes: 0

Views: 1033

Answers (1)

J. Piquard
J. Piquard

Reputation: 1663

Instead of having to create a self.name needed to be initialized for each Node. You could add a self.id initialized with a static counter incremented at each creation.

Step 1 - add a static counter and initialize the self.id attribute

The counterstarts from 0 and is accessible through Node.counter.

class Node():
    counter = 0
    def __init__(self, key = None, prev = None, next = None):
        Node.counter += 1
        self.id = Node.counter
        self.key = key
        self.prev = prev
        self.next = next

Step 2 - modify the __str__ function to get the id of prev and next

The name of the self.prev and self.next is only displayed when not None.

Recover the name of the class with self.__class__.__name__.

def __str__(self):
    sprev = repr(self.prev)
    if self.prev != None :
        sprev = '%s%d' % (self.__class__.__name__, self.prev.id)
    snext = repr(self.next)
    if self.next != None :
        snext = '%s%d' % (self.__class__.__name__, self.next.id)
    return ('[%s][%d][%s]' % (sprev, self.key, snext))

Here are some examples:

>>> node1 = Node(21)
>>> print(node1)
[None][21][None]
>>> node2 = Node(10,node1)
>>> print(node2)
[Node1][10][None]
>>> node3 = Node(11,node2,node1)
>>> print(node3)
[Node2][11][Node1]

Upvotes: 1

Related Questions