c++ - Pointers to pointers: partitioning a linked list -
i'm trying become more facile pointers. so, fun, took following c++ function partitions linked list around value
void partitionlist(lnode<int> *& head, int val) { lnode<int> * front = nullptr; lnode<int> * = nullptr; lnode<int> * curr = head; while (curr) { lnode<int> * next = curr->next; if (curr->data < val) { curr->next = front; front = curr; } else { curr->next = back; = curr; } curr = next; } curr = front; while (curr->next) { curr = curr->next; } curr->next = back; head = front; }
and tried change take c-style double pointer instead. did mindless find-replace, didn't work. looking it, found source of problem, still don't understand what's going on...
void partitionlist(lnode<int> ** head, int val) { lnode<int> * front = nullptr; lnode<int> * = nullptr; lnode<int> ** curr = head; while (*curr) { lnode<int> * entry = *curr; std::cout << (*curr)->data << std::endl; // on second loop, prints 2 std::cout << entry->data << std::endl; // on second loop, prints 2 lnode<int> * next = entry->next; // assignment std::cout << entry->data << std::endl; // on second loop, prints 2 std::cout << (*curr)->data << std::endl; // on second loop, prints 3! if ((*curr)->data < val) { (*curr)->next = front; front = *curr; } else { (*curr)->next = back; = *curr; } curr = &next; } *curr = front; while ((*curr)->next) { (*curr) = (*curr)->next; } (*curr)->next = back; head = &front; } int main() { lnode<int> * tail = new lnode<int>(8, nullptr); lnode<int> * 7 = new lnode<int>(7, tail); lnode<int> * 6 = new lnode<int>(6, seven); lnode<int> * 5 = new lnode<int>(5, six); lnode<int> * 4 = new lnode<int>(4, five); lnode<int> * 3 = new lnode<int>(3, four); lnode<int> * 2 = new lnode<int>(2, three); lnode<int> * head = new lnode<int>(1, two); partitionlist(&head, 6); }
on first loop, 4 of debug print lines near top of function's while loop print "1". however, on second loop, print "2", "2", "2", "3"?
can explain what's going on? what's right way use double pointer instead of reference pointer?
thanks!
void partitionlist(lnode<int> *& head, int val) { ... head = front; // <= head modified }
but here not
void partitionlist(lnode<int> ** head, int val) { ... head = &front; // try *head = front }
and if want quick replace this
void partitionlist(lnode<int> *& head, int val) { ... lnode<int> * curr = head;
just write this:
void partitionlist(lnode<int> ** head, int val) { ... lnode<int> * curr = *head;
why did modify *cur
**cur
?
Comments
Post a Comment