|
| 1 | +class LinkedList(): |
| 2 | + def __init__(self, value=None): |
| 3 | + self.value = value |
| 4 | + # 前驱 |
| 5 | + self.before = None |
| 6 | + # 后继 |
| 7 | + self.behind = None |
| 8 | + |
| 9 | + def __str__(self): |
| 10 | + if self.value is not None: |
| 11 | + return str(self.value) |
| 12 | + else: |
| 13 | + return 'None' |
| 14 | + |
| 15 | + |
| 16 | +def init(): |
| 17 | + return LinkedList('HEAD') |
| 18 | + |
| 19 | + |
| 20 | +def delete(linked_list): |
| 21 | + if isinstance(linked_list, LinkedList): |
| 22 | + if linked_list.behind is not None: |
| 23 | + delete(linked_list.behind) |
| 24 | + linked_list.behind = None |
| 25 | + linked_list.before = None |
| 26 | + linked_list.value = None |
| 27 | + |
| 28 | + |
| 29 | +def insert(linked_list, index, node): |
| 30 | + node = LinkedList(node) |
| 31 | + if isinstance(linked_list, LinkedList): |
| 32 | + i = 0 |
| 33 | + while linked_list.behind is not None: |
| 34 | + if i == index: |
| 35 | + break |
| 36 | + i += 1 |
| 37 | + linked_list = linked_list.behind |
| 38 | + if linked_list.behind is not None: |
| 39 | + node.behind = linked_list.behind |
| 40 | + linked_list.behind.before = node |
| 41 | + node.before, linked_list.behind = linked_list, node |
| 42 | + |
| 43 | + |
| 44 | +def remove(linked_list, index): |
| 45 | + if isinstance(linked_list, LinkedList): |
| 46 | + i = 0 |
| 47 | + while linked_list.behind is not None: |
| 48 | + if i == index: |
| 49 | + break |
| 50 | + i += 1 |
| 51 | + linked_list = linked_list.behind |
| 52 | + if linked_list.behind is not None: |
| 53 | + linked_list.behind.before = linked_list.before |
| 54 | + if linked_list.before is not None: |
| 55 | + linked_list.before.behind = linked_list.behind |
| 56 | + linked_list.behind = None |
| 57 | + linked_list.before = None |
| 58 | + linked_list.value = None |
| 59 | + |
| 60 | + |
| 61 | +def trave(linked_list): |
| 62 | + if isinstance(linked_list, LinkedList): |
| 63 | + print(linked_list) |
| 64 | + if linked_list.behind is not None: |
| 65 | + trave(linked_list.behind) |
| 66 | + |
| 67 | + |
| 68 | +def find(linked_list, index): |
| 69 | + if isinstance(linked_list, LinkedList): |
| 70 | + i = 0 |
| 71 | + while linked_list.behind is not None: |
| 72 | + if i == index: |
| 73 | + return linked_list |
| 74 | + i += 1 |
| 75 | + linked_list = linked_list.behind |
| 76 | + else: |
| 77 | + if i < index: |
| 78 | + raise Exception(404) |
| 79 | + return linked_list |
| 80 | + |
| 81 | + |
| 82 | +linked_list = init() |
| 83 | +trave(linked_list) |
| 84 | +# delete(linked_list) |
| 85 | +insert(linked_list, 0, 1) |
| 86 | +insert(linked_list, 0, 2) |
| 87 | +insert(linked_list, 0, 3) |
| 88 | +remove(linked_list,2) |
| 89 | +trave(linked_list) |
| 90 | +print(find(linked_list,3)) |
0 commit comments