Skip to content

Refactor: Memory Efficient Doubly Linked List #692

@Zehen-249

Description

@Zehen-249

📌 Current Implementation

The linked list currently uses two separate pointers (next, prev) for each node:

new_node = LinkedListNode(key, data,
                          links=['next', 'prev'],
                          addrs=[None, None])

While this is clean and flexible (thanks to dynamic links and __slots__), it uses more memory per node, especially in large lists.


💡 Suggested Improvement

Use a single pointer both instead of next and prev to store the XOR of adjacent node addresses:

# XOR of previous and next node ids:
new_node.both = id(prev) ^ id(next)

This reduces memory consumption while still allowing bidirectional traversal.

Existing design (passing links dynamically and customizing slots) makes this refactor easier, as we only need:

links = ['both']
addrs = [0]  # Initial XOR

✨ Benefits

Memory Efficient: Reduces pointer storage from 2 to 1 per node.
Demonstrates Advanced Technique: Shows how low-level pointer tricks can be adapted even in Python.
Backward Compatible: We could optionally provide a flag (mode='xor') to toggle between standard and XOR-based behavior.

⚠️ Notes / Considerations

Python doesn’t support pointer arithmetic directly — so we'll need to maintain a dictionary like:

self._nodes = {}  # id(node): node

to dereference id() values.
Need to handle None safely, using 0 as a placeholder in XOR ops.


🛠️ Task Outline

  • Add mode='xor' option to the Linked List class.
  • Create a new LinkedListNode with links=['both'] and store XOR of ids.
  • Maintain an internal id_to_node dictionary to simulate pointer access.
  • Refactor insert_after, traverse, and other methods accordingly.
  • Add unit tests comparing standard and XOR list behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions