Data structure and algorithms

Beej beej at beej.us
Mon Jan 29 13:30:16 EST 2007


On Jan 28, 2:56 pm, "azrael" <jura.gro... at gmail.com> wrote:
> class Node:
>   def __init__(self, cargo=None, next=None):
>     self.cargo = cargo
>     self.next  = next

This is OK for the node itself, but maybe you should try writing a 
LinkedList class that you use:

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

    def append(self, node):
        ...

    def remove(self, node):
        ...

>>> ll = LinkedList()
>>> ll.append(Node(3490))

(For extra fun, make it so you can iterate over the linked list and 
call it like this:    for n in ll: print n   :-) )

> >>> list=[]
> >>> list.append(Node(1))
> >>> list.append(Node(2))
> >>> list[0].next=list[1]
> >>> list.append(Node(3))
> >>> list[1].next=list[2]

I'd classify this as "not pretty".  Sure, it's more "dynamic" in that 
you don't have a variable to reference every node, but it's way 
cleaner to make an encapsulating LinkedList class, right?

In in Python, references to objects are very much like pointers in C:

>>> foo = Node(3490)  # foo is a reference to a Node instance
>>> bar = foo   # bar points to the same Node instance as foo
>>> foo
<__main__.Node object at 0xb7b362ec>
>>> bar
<__main__.Node object at 0xb7b362ec>

See?  They point to the name Node object.

> I think that my concept is wrong by using a list to create a list.

I agree with you, if your goal is to implement your own list.  Using 
the Python functionality just makes things less clear.

> Is
> it possible to manage the insertation of new object like in C by
> allocating new memory space.

Absolutely.  The "next" pointer thing is the way to go, so you're on 
the right track with that.

When deleting nodes from the list, you don't explicitly delete them; 
you just need to remove all your references to them.  Nodes will be 
garbage collected when there are no more references to them anywhere.

> any sugestions how to make the implementation more like in C. I never
> managed the syntax of C so I stoped when structs crossed my way.
> Please help. I dont want to learn C.

Ah, it's a pity.  C is my favorite compiled procedural language.

-Beej




More information about the Python-list mailing list