list insertion

Bengt Richter bokr at oz.net
Sat Aug 27 21:44:09 EDT 2005


On Tue, 23 Aug 2005 20:58:11 -0700, Randy Bush <randy at psg.com> wrote:

>i am trying to insert into a singly linked list
>
>    hold = self.next
>    self.next = DaClass(value)
>    self.next.next = hold
>
>but i suspect (from print statement insertions) that the result
>is not as i expect.  as the concept and code should be very
>common, as i am too old for pride, i thought i would ask.
>
I think you're fine. Here's some possible context for your code:

 >>> class DaClass(object):
 ...     def __init__(self, value):
 ...         self.value = value
 ...         self.next = None
 ...     def values(self):
 ...         while True:
 ...             yield self.value
 ...             if self.next is None: break
 ...             self = self.next
 ...     def insert(self, value):
 ...         hold = self.next
 ...         self.next = DaClass(value)
 ...         self.next.next = hold
 ...         return self
 ...     def __repr__(self):
 ...         return '<DaClass %s>'%(' -> '.join(map(repr, self.values())))
 ...
 ...
 >>> sll = DaClass(1)
 >>> sll
 <DaClass 1>
 >>> sll.insert(2)
 <DaClass 1 -> 2>
 >>> sll
 <DaClass 1 -> 2>
 >>> sll.insert('a')
 <DaClass 1 -> 'a' -> 2>
 >>> sll.next
 <DaClass 'a' -> 2>
 >>> sll.next.insert('b')
 <DaClass 'a' -> 'b' -> 2>
 >>> sll
 <DaClass 1 -> 'a' -> 'b' -> 2>

Regards,
Bengt Richter



More information about the Python-list mailing list