【问题标题】:How do I actually remember the address pointed by pointer?我如何真正记住指针指向的地址?
【发布时间】:2021-02-03 07:54:30
【问题描述】:

使用链表,我正在执行以下操作:

struct Node {
    int val;
    struct Node* prev;
    struct Node* next;
};


struct Node* head;
struct Node* tail;
struct Node* temp;

其中Node是链表的结构,head指向第一个元素,tail指向最后一个元素,temp用于中间计算。

move_function(address1, address2) 实际上通过适当地更改它们的 prev、next 指针来交换地址 1 和 2 处的节点。

void move(struct Node* t1, struct Node* t2)  //known that t1->next ..... ->next = t2, move from t2 to t1

{
    cout << "move";

    if (t1->next == t2)
    {
        cout << " Conseq";
        temp1 = t1->prev;
        temp2 = t2->next;

        t1->next = temp2; if (temp2 != NULL) temp2->prev = t1;
        t2->prev = temp1; if (temp1 != NULL) temp1->next = t2;
        t2->next = t1;
        t1->prev = t2;

    }

    else

    {
        cout << "...";

        t2->prev->next = t2->next;

        if (t2->next != NULL) { t2->next->prev = t2->prev; }

        if (t1 != head) { t1->prev->next = t2; t2->prev = t1->prev; t2->next = t1; t1->prev = t2; }

        else { head = t2; t2->prev = NULL; t2->next = t1; t1->prev = t2; }
    }

}
if (<node to be shifted is the last one i.e. *tail*>)
    
{    
    temp = tail->prev;    
    move_function (head, tail);    
    tail= temp;
    
}

事实证明,在编写temp = tail-&gt;prev; temp 时保留了定义,而不是我想要的,即它后面的元素的地址(移动后需要设置为尾部)。更具体地说,最后,在执行 move_function (head, tail); tail=temp; 之后,与我想要的相反,对于列表中的元素数 = =2,tail-&gt;prev == NULL is true. 我真正想要的是记住移动后的最后一个元素。

这里发生了什么,我该如何解决?在写作时,temp = tail-&gt;prev,如果 tail 处的节点移动到 head 位置并且其 prev 设置为 NULL,temp-&gt;prev 是否会变为 @ 987654331@?

谢谢!

【问题讨论】:

标签: c++ pointers


【解决方案1】:

这就是为什么在一行中声明多个变量是个坏主意。问题是只有head 是一个指针。 IE。以下两段代码是等价的:

// The way you declared the variables:
struct Node* head, tail, temp;

// Above is equivalent to:
struct Node* head;
struct Node tail;
struct Node temp;

只需在单独的行上定义每个变量。它将使代码更具可读性并同时对其进行修复。

您的声明问题的现场演示:https://godbolt.org/z/f154dT

编辑:另外,由于您编写的是 C++,而不是 C,因此没有理由将 struct 放在那里。只需使用Node * head;

【讨论】:

  • 对不起,我写错了。我实际上宣布了您建议的方式
  • 在这种情况下,请提供一个可重现的最小示例,以便我们实际检查发生了什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多