Skip to content

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

@Baxayesh

Description

@Baxayesh

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;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions