两个指向相同值的指针,只改变其中一个——c++中的双链表
2 Pointers to same value and changing just one of them - Double linked list C++
我有一个具有这些属性的class Node
:
int value;
Node* next;
Node* prev;
当我初始化列表以知道哪个是第一个节点时,我有一个具有属性Node* first
的class 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留在那里?我想如果我把两个指针指向一个Node,我可以移动其中一个指针而不触及另一个指针的属性。
我知道这是一个愚蠢的问题,但我想不出来!初始
aux1 -->|---|<--|---|
aux3 -->| 1 |-->| 2 |
|___| |___|
aux2 -->|---|<--|---|
aux4 -->| 6 |-->| 7 |
|___| |___|
after aux1->next = aux2->next
aux1 -->|---|<--- |---|
aux3 -->| 1 | | 2 | (no longer anything pointing at 2)
|___| |___|
aux2 -->|---| > |---|
aux4 -->| 6 | ---> | 7 |
|___| <--- |___|
after aux1->next->prev = aux1;
aux1 -->|---|<--- |---|
aux3 -->| 1 |---> | 7 |
|___| /> |___|
/
aux2 -->|---| /
aux4 -->| 6 |/
|___|
打印aux3->next
好的,我想我明白你现在在尝试什么,你会想要缓存第二个节点在第一个列表,而你操作它:
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 |
|___| |___|
相关文章:
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 链表,反向函数,数据结构
- 使用std::list创建循环链表
- 链表的泛型函数remove()与成员函数remove)
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 我们可以删除链表中静态内存中的节点吗
- C++,指针数组,指向双链表中的条目
- 链表中写入访问冲突的未知原因
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 打印所有链表的元素 (C++)
- 错误:需要类名(链表c++)
- 为什么C中的通用链表中存储的数据已损坏
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 链表c++插入,所有情况都已检查,但没有任何工作
- 链表,将列表复制到另一个列表
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 对单向链表进行排序时出现运行时错误