c++ - Deleting a node from a linked list without getting an error? -
c++ - Deleting a node from a linked list without getting an error? -
simply, programme create linked list of chars string. (say "hello" head->h->e->l->l->o->null) whenever seek delete head using erase function, programme stop working giving "application.exe has stopped working... windows checking solution..". think might have problem memory allocation can't tell. suggestions appreciated.
this works
void stringadt::append(string s) { (int = 0; < s.length(); i++) { node* nodeptr; node* newnode; newnode = new node; newnode->data = s.at(i); newnode->next = null; if (!head) { head = newnode; } else { nodeptr = head; while (nodeptr->next) { nodeptr = nodeptr->next; } nodeptr->next = newnode; } } } void stringadt::erase(int pos) //pos = position erase { if (!head || pos < 0 || pos > length() - 1) return; else { node* nodeptr; nodeptr = head; if (pos == 0) { nodeptr = head->next; delete head; //problem comes after execution of line!! } }
}
here class
class stringadt{ private: struct node { char data; node* next; }; node* head;
here append function may root of problem because of memory allocation.
void stringadt::append(string s) (appending string s linked list) { node* nodeptr; int slength = s.length(); node *nodearray; nodearray = new node[slength]; if(!nodearray) return; (unsigned = 0; < s.length(); i++) { nodearray[i].data = s.at(i); nodearray[i].next = null; } if (!head) { head = nodearray; nodeptr = head; for(unsigned count = 1; count < slength; count ++) { nodeptr->next = (nodearray + count); nodeptr = nodeptr->next; //cout << "number of count " << count << endl; } } else { nodeptr = head; while (nodeptr->next) { nodeptr = nodeptr->next; } for(unsigned count = 0; count < slength; count ++) { nodeptr->next = (nodearray + count); nodeptr = nodeptr->next; //cout << "number of count " << count << endl; } }
}
the erase function should this:
if (pos == 0) { nodeptr = head; head = head->next; delete nodeptr; }
c++ list linked-list
Comments
Post a Comment