簡體   English   中英

XOR 雙向鏈表

[英]XOR Doubly Linked List

因此,我正在嘗試創建一個 XOR 雙向鏈表作為練習的一部分,但我的 removeFirst() 函數不斷出現分段錯誤。 我無法弄清楚出了什么問題,有人有線索嗎?

這是一個節點的樣子:

class Node{

public:
    int data;
    Node *XOR;

};

我正在使用此函數來計算 XOR:

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

這是我的 XOR 雙向鏈表類:

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 分段錯誤(核心轉儲)

deletemalloc的數據。 你需要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);
      }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM