insert - Append linked list with recursion -
i want insert function calls private recursive insert function adds next number end of linked list. having trouble on parameters should use , should in recursive insert function. thinking recursive insert function needs node pointer step through recursively.
class linkedlist{ private: struct node{ int data; //stores data in nodes node* next; ~node(){delete next;} }; public: linkedlist(){ first = null;} ~linkedlist(){delete first;} void print() const { print( first ); } void insert(const int d){ //here first insert method insert(first, d); } private: node* first; here function stuck on...
void insert(node* p, const int d){ //this private recursive 1 node* temp = new node; temp->data=d; if(p->next == null) p->next = temp; else insert(p->next, d); } }; int main() { int a[] = { 1, 2, 3, 4, 5, 6}; linkedlist list; for(int i=0; i<6; i++) list.insert( a[i] ); } i want know how insert function overload getting parameters different. want know if stepping through recursive function correctly.
the function calls recursive function should
void insert(const int d){ insert(first, d); } the recursive function should like
void insert(node*& p, const int d){ node* temp = new node; temp->data=d; if(p == null) p = temp; else insert(p->next, d); }
Comments
Post a Comment