Algorithms using Python?
Ian Kelly
ian.g.kelly at gmail.com
Fri Sep 21 16:07:01 EDT 2012
On Fri, Sep 21, 2012 at 1:45 PM, Dennis Lee Bieber
<wlfraed at 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.
More information about the Python-list
mailing list