How to implement an XOR Linked List in Python?

 ̄綄美尐妖づ 提交于 2019-12-11 07:06:00

问题


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 list in Python ? if yes how ?


回答1:


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.



来源:https://stackoverflow.com/questions/46401486/how-to-implement-an-xor-linked-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!