异或双向链表

XOR Doubly Linked List

本文关键字:双向链表      更新时间:2023-10-16

所以我正在尝试创建一个异或双向链表作为练习的一部分,但我的removeFirst()函数不断出现分割错误。我无法弄清楚出了什么问题,有人知道吗?

节点的样子如下:

class Node{
public:
    int data;
    Node *XOR;
};

我正在使用此函数来计算异或:

Node* returnXOR(Node *a, Node *b){
    return (Node*)((uintptr_t) (a) ^ (uintptr_t) (b));
}

这是我的异或双向链表类:

class XORDLL{
public:
Node *head;
XORDLL(){
    head = NULL;
}
void addFirst(int data){
    // Make a newNode pointer
    Node *newNode = new Node;
    // Set the variables
    newNode->data = data;
    newNode->XOR = returnXOR(head, NULL);   
    // If the head is not empty set the XOR of the head to the next XOR the newNode
    if(head != NULL){
        head->XOR = returnXOR(newNode, returnXOR(head->XOR, NULL));
    }   
    // Set the newNode to the head 
    head = newNode;
}
void removeFirst(){
    // If head is equal to NULL, do nothing
    if(head == NULL){
        return;
    }
    // Store current head
    Node *tmp = head;
    // Set head equal to the next address
    head = returnXOR(tmp->XOR, NULL);
    head->XOR = returnXOR(tmp->XOR, tmp);

    // Delete tmp variable
    delete tmp;
}
void printList(){
    Node *current = head;
    Node *prev = NULL;
    Node *next;
    while(current != NULL){
        printf("%d ", current->data);
        next = returnXOR(current->XOR, prev);
        prev = current;
        current = next;           
    }
    printf("n");
}
};

当我运行这段代码时:

int main(){
    XORDLL l;
    l.addFirst(1);
    l.addFirst(2);
    l.addFirst(3);
    l.printList();
    l.removeFirst();
    l.printList();
    return 0;
}

这是输出:

3 2 1分段故障(核心转储)

delete malloc'ed数据。您需要改为free它,或者使用 new 而不是 malloc 。另一个错误是您错过了这一行:

          void removeFirst(){
          // If head is equal to NULL, do nothing
          if(head == NULL){
              return;
          }
          // Store current head
          Node *tmp = head;
          // Set head equal to the next address
          head = returnXOR(tmp->XOR, NULL);
          head->XOR = returnXOR(head->XOR, tmp); <<<<<<<<<<<<<<<<<< Here
          // Free tmp variable
          free(tmp);
      }