Singly-linked list/Element definition: Difference between revisions
Content deleted Content added
m →{{header|Python}}: Colourize |
|||
Line 244:
The Node class implements also iteration for more Pythonic iteration over linked lists.
<python>
class LinkedList(object):
def __init__(self, value, next=None):▼
"""USELESS academic/classroom example of a linked list implemented in Python.
self.value = value▼
Don't ever consider using something this crude! Use the built-in list() type!
self.next = next▼
class Node(object):
def __init__(self, item):
if item is not None:
self.head = Node(item); self.tail = self.head
else:
self.head = None; self.tail = None
def append(self, item):
if not self.head:
self.head = Node(item)
self.tail = self.head
elif self.tail:
self.tail.next = Node(item)
self.tail = self.tail.next
else:
self.tail = Node(item)
def __iter__(self):
cursor = self.head
while cursor:
yield cursor.value
cursor = cursor.next
</python>
'''Note:''' As explained in this class' docstring implementing linked lists and nodes in Python is an utterly pointless academic exercise. It may give on the flavor of the elements that would be necessary in some other programming languages (''e.g.'' using Python as "executable psuedo-code"). Adding methods for finding, counting, removing and inserting elements is left as an academic exercise to the reader. For any practical application use the built-in ''list()'' or ''dict()'' types as appropriate.
=={{header|Ruby}}==
|