-
Notifications
You must be signed in to change notification settings - Fork 10
Open
Description
for this function:
List::Node *List::make_copy(List::Node *p) { return p ? new Node(p->data, p->prev, make_copy(p->next)) : NULL;}consider we have a linked list like this in heap:
`1
0. address: prev | value | next
- X001: null | 10 | X002
- X002: X001 | 20 | X003
- X003: X002 | 30 | null
by calling function:
- 1.stack frame : P = X001 return ?
-
- p != null --> calling make_copy again :
- 2.stack frame : P = X002 return ?
-
- p != null --> calling make_copy again :
- 3.stack frame : P = X003 return ?
-
- p != null --> calling make_copy again :
- 4.stack frame : P = null return ?
-
- p == null --> return null
so in third stack frame : p = X003
-
return : new Node(p->data, p->prev, (return of fourth stack frame [null]) )
-
-->consider new memory block is : X103 : X002 | 30 | nullin second stack frame : p = X002
-
return : new Node(p->data, p->prev, (return of third stack frame [X103]) )
-
->consider new memory block is : X102 : X001 | 20 | X103in first stack frame : p = X002
-
return : new Node(p->data, p->prev, (return of second stack frame [X102]) )
-
->consider new memory block is : X101 : null | 10 | X102
now heap is:
- -first list:
- X001: null | 10 | X002
- X002: X001 | 20 | X003
- X003: X002 | 30 | null
- -second list:
- X101: null | 10 | X102
- X102: X001 | 20 | X103
- X103: X002 | 30 | null
and as you see prev pointers of any node in second list are pointing to first list elements!!
I guess this can solve problem:
List::Node *List::make_copy(List::Node *p) {
if( p == nullptr )
return nullptr;
Node* tail = make_copy(p->next);
Node* head = new Node(p->data, nullptr, tail);
if(tail != nullptr)
tail->prev = head;
return head;
}Metadata
Metadata
Assignees
Labels
No labels