我有一个具有这些属性的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 |
|___| |___|