异或双向链表
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);
}
相关文章:
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 如何实现容纳整数和无效指针的双向链表?
- 为什么我的双向链表删除函数会删除多个节点?
- 我对数据结构、双向链表有一些问题
- C++ 双向链表:使用矩阵类成员创建和填充列表
- 在 c++ 中具有向量的双向链表构造函数
- 如何在双向链表上实现复制赋值?
- 在C++中删除双向链表的头节点后出现访问冲突异常
- 在双向链表中实现 Popback
- 在C++中反转双向链表
- 双向链表 - 无法删除第一个节点
- 我当前实现的双向链表类是否需要重构迭代器 end() 功能?
- 双向链表 std::unique_ptr 类在节点删除时无法按预期工作
- C++ 双向链表 - 插入同时保持递增顺序
- 如何找到双向链表的最大元素?
- 如何实现双向链表的迭代器?
- 双向链表问题 - 包含项目但不显示
- 双向链表未正确打印值
- 插入到双向链表中的特定位置
- 如何在双向链表的网格中旋转列