【问题标题】:Is it possible to implement XOR LinkedList in Java(DLL with single pointer) [duplicate]是否可以在 Java 中实现 XOR LinkedList(带有单指针的 DLL)[重复]
【发布时间】:2016-01-22 17:55:55
【问题描述】:

XOR 链表基本上是链表的有效版本,它存储前一个和下一个节点的地址,以仅使用单个指针来实现双链表。 我想知道是否可以在 Java 中实现,因为它没有指针。 在 C 中,这可以通过

 /* Insert a node at the begining of the XORed linked list and makes the
    newly inserted node as head */
void insert(struct node **head_ref, int data)
{
    // Allocate memory for new node
    struct node *new_node  = (struct node *) malloc (sizeof (struct node));
    new_node->data = data;

    /* Since new node is being inserted at the begining, npx of new node
       will always be XOR of current head and NULL */
    new_node->npx = XOR(*head_ref, NULL);

    /* If linked list is not empty, then npx of current head node will be XOR 
       of new node and node next to current head */
    if (*head_ref != NULL)
    {
        // *(head_ref)->npx is XOR of NULL and next. So if we do XOR of 
        // it with NULL, we get next
        struct node* next = XOR((*head_ref)->npx,  NULL);
        (*head_ref)->npx = XOR(new_node, next);
    }

    // Change head
    *head_ref = new_node;
}

【问题讨论】:

  • 在 Java 中通常不可能对指针执行算术运算,因为它们总是被视为对对象的引用,而不是数字。
  • 我很好奇任何双向链表在 Java 中的实现可能是什么,它是否已经在做一些类似于 OP 的事情?
  • 这个问题是在微软面试时问我的,我很震惊,用单指针实现双向链表是可能的
  • 您是否可以在数组中使用索引而不是实际指针?反正差别不是很大..

标签: java xor-linkedlist


【解决方案1】:

不,您根本无法在 Java 中执行此操作——您无法获取对象的地址或从其他值计算对对象的引用。这允许垃圾收集器在不干扰程序的情况下移动对象。

这在 C++ 中也是一个非常糟糕的主意。

如果您担心链表中的内存开销,您可以在每个节点存储多个项目。如果一个节点有 prev、next 和 items[16] 引用,并且您始终确保您的节点至少有一半已满,那么平均而言,它将使用比 XOR 列表更少的内存。

【讨论】:

  • 您能否详细说明一下,如果您在每个节点存储多个项目,这不会产生开销吗?我不明白这一点
  • 通常,Java中的链表节点有3个引用(prev、next、item)和对象头,所以它有4个引用大。对于您添加的每个项目,这是 4 个单词的开销。 xor 列表对于您添加的每个项目都有 3 个单词。每个节点有 16 个项目的列表,所有节点至少半满(存在 8 个项目),每个节点有 21 个单词,但是您至少除以 8 个项目以获得 21/8(少于 3)个单词的每个项目开销
  • 哦,我忘记了存储计数和/或在每个节点中启动的词,所以 22/8。还是更小
猜你喜欢
  • 2012-04-15
  • 2016-09-11
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-22
  • 1970-01-01
相关资源
最近更新 更多