Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

a little bug in : 14_LinkedLists/02_OOLinkedListWithIterator.cpp #1

Open
Baxayesh opened this issue May 29, 2021 · 0 comments
Open

Comments

@Baxayesh
Copy link

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

  1. X001: null | 10 | X002
  2. X002: X001 | 20 | X003
  3. 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 | null
    

    in 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 | X103
    

    in 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:
  1. X001: null | 10 | X002
  2. X002: X001 | 20 | X003
  3. X003: X002 | 30 | null
  • -second list:
  1. X101: null | 10 | X102
  2. X102: X001 | 20 | X103
  3. 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant