Singly-linked list/Element definition: Difference between revisions
Content deleted Content added
m →{{header|Python}}: Colourize |
|||
Line 244: | Line 244: | ||
The Node class implements also iteration for more Pythonic iteration over linked lists. |
The Node class implements also iteration for more Pythonic iteration over linked lists. |
||
<python> |
<python> |
||
class LinkedList(object): |
|||
⚫ | |||
"""USELESS academic/classroom example of a linked list implemented in Python. |
|||
⚫ | |||
Don't ever consider using something this crude! Use the built-in list() type! |
|||
⚫ | |||
""" |
|||
class Node(object): |
|||
node = self |
|||
def __init__(self, item): |
|||
while node: |
|||
⚫ | |||
yield node |
|||
⚫ | |||
node = node.next</python> |
|||
⚫ | |||
(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}}== |
=={{header|Ruby}}== |