How to implement an XOR Linked List in Python?

后端 未结 1 1635
小鲜肉
小鲜肉 2021-01-25 13:33

Given that python objects are only a reference to the actual memory Objects and memory address of objects cannot be retrived.

Is it possible to implement an XOR linked

相关标签:
1条回答
  • 2021-01-25 14:17

    You can't build an XOR linked list in Python, since Python doesn't let you mess with the bits in pointers.

    You don't want to implement that anyway -- it's a dirty trick that makes your code hard to understand for little benefit.

    If you're worried about memory, it's almost always better to use a doubly-linked list with more than 1 element per node, like a linked list of arrays.

    For example, while an XOR linked list costs 1 pointer per item, plus the item itself, A doubly-linked list with 16 items per node costs 3 pointers for each 16 items, or 3/16 pointers per item. (the extra pointer is the cost of the integer that records how many items are in the node) That is less than 1. In Python there are additional overheads, but it still works out better.

    In addition to the memory savings, you get advantages in locality because all 16 items in the node are next to each other in memory. Algorithms that iterate through the list will be faster.

    Note that an XOR-linked list also requires you to allocate or free memory each time you add or delete a node, and that is an expensive operation. With the array-linked list, you can do better than this by allowing nodes to be less than completely full. If you allow 5 empty item slots, for example, then you only have allocate or free memory on every 3rd insert or delete at worst.

    0 讨论(0)
提交回复
热议问题