gpt4 book ai didi

c++ - 2 个指向相同值的指针并仅更改其中一个 - 双链表 C++

转载 作者:行者123 更新时间:2023-11-28 02:43:11 25 4
gpt4 key购买 nike

我有一个具有这些属性的 class Node:

int value;
Node* next;
Node* prev;

当我初始化列表以了解哪个是第一个节点时,我有一个带有属性 Node* firstclass List

假设我已经使用这些值初始化了 2 个 class List 列表:

list1: 1 | 2 | 3 | NULL
list2: 6 | 7 | 8 | NULL

我想得到列表“编织”的结果:

list1: 1 | 7 | 3 | NULL
list2: 6 | 2 | 8 | NULL

我将使用此方法list1:

void List::test(List list2){
Node* aux1 = first; //first is 1
Node* aux3 = first; //first is 1
Node* aux2 = list2.first; //first of list2 is 6
Node* aux4 = list2.first; //first of list2 is 6

aux1->next = aux2->next; //aux1->next is now 7 PERFECT
aux1->next->prev = aux1; //aux1->next->prev is now 1 PERFECT

//NOW I WANT TO CHECK aux3->next
cout << aux3->next <<endl;
//IT PRINTS 7, LIKE AUX1->NEXT, BUT I WANT IT TO BE 2, LIKE IF IT'S BEEN DONE TO THE ORIGINAL LIST1!!
}

我怎样才能让 aux3 留在那儿?我想如果我将 2 个指针指向一个节点,我可以移动其中一个指针而不触及另一个指针的属性。

我知道这是个愚蠢的问题,但我想不通!

最佳答案

初始

aux1 -->|---|<--|---|
aux3 -->| 1 |-->| 2 |
|___| |___|

aux2 -->|---|<--|---|
aux4 -->| 6 |-->| 7 |
|___| |___|

aux1->next = aux2->next 之后

aux1 -->|---|<--- |---|
aux3 -->| 1 |\ | 2 | (no longer anything pointing at 2)
|___| \ |___|
\
aux2 -->|---| \> |---|
aux4 -->| 6 | ---> | 7 |
|___| <--- |___|

aux1->next->prev = aux1; 之后

aux1 -->|---|<---  |---|
aux3 -->| 1 |---> | 7 |
|___| /> |___|
/
aux2 -->|---| /
aux4 -->| 6 |/
|___|

打印 aux3->next

7

编辑:

好的,我想我明白你现在正在尝试什么了,你将希望在操作它时将第二个节点缓存在第一个列表中:

Node* aux1 = list1.first;   //first of list1 is 1
Node* aux2 = list2.first; //first of list2 is 6
Node* aux3 = first->next; //aux3 is 2

aux1->next = aux2->next; //aux1->next is now 7 PERFECT
aux1->next->prev = aux1; //aux1->next->prev is now 1 PERFECT

现在你需要使用存储在 aux 3 中的缓存 2 来重新获得你的第二个列表

aux2->next = aux3;
aux3->prev = aux2;

所以你现在应该看到:

aux1 -->|---|<--|---|
| 1 |-->| 7 |
|___| |___|

aux2 -->|---|<--|---|
| 6 |-->| 2 |
|___| |___|

关于c++ - 2 个指向相同值的指针并仅更改其中一个 - 双链表 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25254620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com