I'm making a singly linked list. It has a problem inserting nodes in the middle.
Inserting at the begining and inserting at the end (if done by the void LinkedList::createNode(string aName) function) works fine.Code:void LinkedList::createNode(string aName) { if(startPointer == NULL) { startPointer = new Node;//Node is a struct (*startPointer).next = NULL; (*startPointer).name = aName; } else { Node *temp = startPointer; while((*temp).next != NULL) temp = (*temp).next; (*temp).next = new Node; temp = (*temp).next; (*temp).name = aName; } } void LinkedList::createNode(string aName, unsigned int position) { Node *inserting = new Node(aName); if(position == 0) { (*inserting).next = startPointer;//NOT startPointer->next startPointer = inserting; } else{ Node *temp, *previous; temp = startPointer; for(unsigned int i = 1; i < position; i++) { previous = temp; if((*temp).next != NULL) temp = (*temp).next; else { std::cout << "The end of the list has been reached so the node will be added to the end." << std::endl; createNode(aName); return;//causes method to end prematurally, which we want } }/*This doesn't work*/ Node *inserting = new Node; (*inserting).name = aName; (*inserting).next = temp; std::cout << "done setting where the new node points to" << std::endl; std::cout << "previous->next: " << (*previous).next << std::endl;//crashes here (*previous).next = inserting; std::cout << "done changing where the node before the new node points to (which is the new node)" << std::endl; } }



LinkBack URL
About LinkBacks



