Last active
November 20, 2018 13:58
-
-
Save yoniLavi/287d732b617c220a7d508ab49c1bb47d to your computer and use it in GitHub Desktop.
A reversible Pythonic LinkedList class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class LinkedList: | |
| def __init__(self, collection): | |
| try: | |
| iterator = iter(collection) | |
| head = next(iterator) | |
| self._value = head | |
| tail = LinkedList(iterator) | |
| self._tail = tail | |
| self._len = tail._len + 1 | |
| except StopIteration: | |
| self._len = 0 | |
| def __len__(self): | |
| return self._len | |
| def __iter__(self): | |
| if self: | |
| yield self._value | |
| yield from self._tail.__iter__() | |
| def __reversed__(self): | |
| if self: | |
| yield from self._tail.__reversed__() | |
| yield self._value | |
| def __repr__(self): | |
| return 'LinkedList(%s)' % list(self) | |
| #### alternative, tuple-based approach #### | |
| def linked_list(collection): | |
| try: | |
| iterator = iter(collection) | |
| head = next(iterator) | |
| return head, linked_list(iterator) | |
| except StopIteration: | |
| return None | |
| def reversed_ll(ll): | |
| if not ll: | |
| return ll | |
| prev_pair = None | |
| value, next_pair = ll | |
| while next_pair: | |
| prev_pair = (value, prev_pair) | |
| value, next_pair = next_pair | |
| return prev_pair |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment