因此,作为练习的一部分,我试图创建一个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 分段错误(核心已转储)
答案 0 :(得分:0)
您delete
个malloc
的数据。您需要改为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);
}