pointers - Doubly Linked List insertion infinite loop... C++ -
i implementing doubly linked list in c++. before insertion, printing node function works after insertion front, printing goes forever.
for example, have nodes of 1, 2, 3 data , insert data front 5. try print, , shows 5, 1, infinite loop without going third node 2.
here structure.
struct dl_node { int data; struct dl_node* prev; struct dl_node* next; dl_node(dl_node* prev, dl_node* next, int data) { // here, prev parameter // this->prev object this->prev = prev; this->next = next; this->data = data; } // constructor, without pointer parameter explicit dl_node(int data) { this->prev = this; this->next = this; this->data = data; } };
here insertion function.
// "push-front" operation dl_node* insert_node(dl_node* head, int data) { if (nullptr == head) return new dl_node(data); auto insertion = new dl_node(head->prev, head, data); // previous node of insertion head's prev // next node of insertion head insertion->prev->next = insertion; insertion->next->prev = insertion; return insertion; }
here initialization.
struct dl_node* head = new dl_node(null); struct dl_node* node_1 = new dl_node(null); struct dl_node* node_2 = new dl_node(null); head ->data = 1; head ->next = node_1; node_1->prev = head; node_1->data = 2; node_1->next = node_2; node_2->prev = node_1; node_2->data = 3; node_2->next = nullptr;
here insertion.
// insert front head = insert_node(head, 5);
here printing loop.
struct dl_node* current_node_2 = head; while ( current_node_2 != nullptr ) { cout << current_node_2->data << ", "; current_node_2 = current_node_2->next; } // 5, 1, infinite loop here....
could have idea?
the problem default dl_node
constructor sets both prev
, next
this
.
when call insert_node(head, 5)
end following state:
insertion->prev = head->prev; // assigned in constructor, head->prev == head insertion->next = head; insertion->prev->next = insertion; insertion->next->prev = insertion;
but insertion->prev == head->prev
, , know head->prev == head
, so
insertion->prev->next = insertion
reduces to:
head->next = insertion;
so end list looks this:
insertion -> head -> insertion -> ...
you should change default constructor set both next
, prev
null. in insert function, should check insertion->prev
, insertion->next
non-null before dereferencing them.
Comments
Post a Comment