Singly-linked list/Element definition: Difference between revisions

Line 244:
The Node class implements also iteration for more Pythonic iteration over linked lists.
 
<python>class Node:
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
def __iter__(self): """
class Node(object):
node = self
def __init__(self, item):
while node:
self.value = valueitem
yield node
self.next = nextNone
node = node.next</python>
def __init__(self, value, nextitem=None):
(Note that in Python you would always use the built-in list structure for this task, except for the specific case, such as this, when you are asked to show how you might implement the function without using the list type).
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}}==
Anonymous user