Reputation: 345
I have a class Node
with these attributes:
int value;
Node* next;
Node* prev;
I have a class List
with an attribute Node* first
when I initialize the list to know which one is the first node.
Assuming I have initialized 2 lists of class List
with these values:
list1: 1 | 2 | 3 | NULL
list2: 6 | 7 | 8 | NULL
I want to get to a result where the lists are 'braided':
list1: 1 | 7 | 3 | NULL
list2: 6 | 2 | 8 | NULL
I'll use this method to 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!!
}
How can I make aux3 to stay in there? I thought if I point 2 pointers to just one Node, I could move one of those pointers without touching the attributes of the other pointer.
I know it's a silly problem, but I can't figure it out!
Upvotes: 0
Views: 236
Reputation: 26058
Initial
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 |/
|___|
printing aux3->next
7
EDIT:
OK I think I understand what you are attempting now, you'll want to cache the second node in the first list while you manipulate it:
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
Now you need to use the cached 2 stored in aux 3 to regain your second list
aux2->next = aux3;
aux3->prev = aux2;
so you should now see:
aux1 -->|---|<--|---|
| 1 |-->| 7 |
|___| |___|
aux2 -->|---|<--|---|
| 6 |-->| 2 |
|___| |___|
Upvotes: 2