【发布时间】: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->prev; temp 时保留了定义,而不是我想要的,即它后面的元素的地址(移动后需要设置为尾部)。更具体地说,最后,在执行 move_function (head, tail); tail=temp; 之后,与我想要的相反,对于列表中的元素数 = =2,tail->prev == NULL is true. 我真正想要的是记住移动后的最后一个元素。
这里发生了什么,我该如何解决?在写作时,temp = tail->prev,如果 tail 处的节点移动到 head 位置并且其 prev 设置为 NULL,temp->prev 是否会变为 @ 987654331@?
谢谢!
【问题讨论】:
-
Node是什么样的?temp是什么?你能提供一个minimal reproducible example吗?