【问题标题】:Segmentation fault on XOR linked lists implementationXOR 链表实现的分段错误
【发布时间】:2020-01-26 04:43:00
【问题描述】:

代码非常简单,也许我遗漏了一些明显导致分段错误的内容。乍一看,双向异或链表实现代码(打算)创建三个节点,并以从左到右的方式遍历它们。

#include <iostream>

using namespace std;

typedef struct node { int data = 0; struct node* npx = NULL; }n;

n *zor(n *a, n *b) {
    return (n*)((uintptr_t) a ^ (uintptr_t) b);
}

int main() {

    n *head, *a, *b;

    head = new n;
    a = new n;
    b = new n;

    head->npx = zor(NULL, a);
    a->npx = zor(head, b);
    b->npx = zor(a, NULL);

    n* ptr = head;
    while (ptr != NULL) {
        cout << ptr->data;
        ptr = zor(ptr, ptr->npx);
    }
}

我希望在遍历列表中的所有节点后输出为“000”。

【问题讨论】:

  • 您是否尝试过遍历您的代码?检查您存储在ptr 中的值是否是您认为的值?这似乎比花时间写一个问题更容易自己调试。
  • 恐怕你试图让它有点太简单了,请在ptr = zor(ptr, ptr-&gt;npx); 付款,记住头节点的链接是用NULL, a 设置的,而不是head, aHere's how I explained one of these antique brain-twisters last time.

标签: c++ linked-list doubly-linked-list xor-linkedlist


【解决方案1】:

出了什么问题

链接正确地结合了前一个指针和下一个指针。

link = previous ^ next

可惜后来next指针恢复时

ptr = zor(ptr, ptr->npx);

尝试重构下一个

next = current ^ link

而不是

next = previous ^ link

导致下一个损坏。这意味着您需要更多的簿记来跟踪之前的节点。

可能的解决方案

n* current = head; // changed name to make code match description
n* previous = NULL; // no previous at the head
while (current != NULL) {
    cout << current->data;
    n* next = zor(previous, current->npx); // need a temp so we can update previous
    previous = current; // current becomes the next's previous
    current = next; // advance current to next
}

【讨论】:

  • 我现在明白为什么错误首先出现了。谢谢!
猜你喜欢
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
  • 2020-09-30
  • 2013-10-05
  • 2021-01-17
  • 1970-01-01
相关资源
最近更新 更多