Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #29670
| References | <TYV6s.7304$Vh6.4862@newsfe20.iad> <jngp58p2mq1nrov4l0tj29e891vrg8vo6b@invalid.netcom.com> |
|---|---|
| From | Ian Kelly <ian.g.kelly@gmail.com> |
| Date | 2012-09-21 14:07 -0600 |
| Subject | Re: Algorithms using Python? |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1032.1348258054.27098.python-list@python.org> (permalink) |
On Fri, Sep 21, 2012 at 1:45 PM, Dennis Lee Bieber
<wlfraed@ix.netcom.com> wrote:
> You can probably implement them, but they're not going to be very
> efficient. (And never "remove" an element from the linked-list
> implementation because Python would shift all the other elements, hence
> your "links" become invalid).
I'm not sure what you mean by that last comment.
class Node(object):
def __init__(self, data, next):
self.data = data
self.next = next
class LinkedList(object):
def __init__(self):
self._head = None
def __iter__(self):
node = self._head
while node:
yield node.data
node = node.next
def insert_front(self, value):
self._head = Node(value, self._head)
def remove(self, value):
prior, node = None, self._head
while node:
if node.data == value:
if prior:
prior.next = node.next
else:
self._head = node.next
break
prior, node = node, node.next
else:
raise ValueError("value not found")
>>> li = LinkedList()
>>> for char in 'edcba':
... li.insert_front(char)
...
>>> print ''.join(li)
abcde
>>> li.remove('c')
>>> print ''.join(li)
abde
It seems to work fine to me.
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Algorithms using Python? Mayuresh Kathe <mayuresh@kathe.in> - 2012-09-21 14:26 +0530
Re: Algorithms using Python? Joel Goldstick <joel.goldstick@gmail.com> - 2012-09-21 10:41 -0400
Re: Algorithms using Python? Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2012-09-21 15:45 -0400
Re: Algorithms using Python? Ian Kelly <ian.g.kelly@gmail.com> - 2012-09-21 14:07 -0600
Re: Re: Algorithms using Python? Evan Driscoll <driscoll@cs.wisc.edu> - 2012-09-21 15:43 -0500
Re: Algorithms using Python? Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2012-09-21 17:14 -0400
Re: Algorithms using Python? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-09-22 01:28 +0000
Re: Algorithms using Python? Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2012-09-22 00:29 -0400
Re: Algorithms using Python? Wayne Werner <wayne@waynewerner.com> - 2012-09-26 10:55 -0500
Re: Algorithms using Python? 88888 Dihedral <dihedral88888@googlemail.com> - 2012-09-27 04:15 -0700
Re: Algorithms using Python? 88888 Dihedral <dihedral88888@googlemail.com> - 2012-09-27 04:15 -0700
csiph-web