hi guys. I created a simple code to build linked list.
following are the various files
Header file
Implementation fileCode:class ListBuild { private: struct node { int d; node * next; // next pointer }; typedef node * list; // list == node* list head ,tail,prev; // pointer to head and tail static member static int sz; // current size of list,static member public: ListBuild () ; // default constructor ListBuild (const ListBuild & Lst); // copy constructor ~ListBuild() ; // default destructor int findlength()const; // find size void insert(int newitem); // add node void findpr()const; // previous pointer that tail void remove(); // remove node void print(); // print list };
and the user fileCode:#include <iostream> #include "Link_list_build.h" using namespace std; int ListBuild::sz=0; ListBuild ::ListBuild() // default constructor { head=0; //Null pointer tail=0; prev=0; } ListBuild ::ListBuild(const ListBuild& lst) // copy constructor { } ListBuild ::~ListBuild() // default destructor { remove() ; // call func to remove node memory } int ListBuild::findlength()const // determine current size of list { return sz; } void ListBuild ::insert(int newitem) // add item at start or inbetween { //int newlngth= findlength()+1; // creates new node structure and returns pointer to it list newnode = new node ; if( newnode ==NULL) cout<< " could not allocate memory"; else { sz= findlength(); newnode->d = newitem; newnode->next=NULL; if (sz==0) // allocate first node { head= newnode; tail=head; } else // allocate rest nodes { tail->next = newnode; tail=newnode; } sz++; } // end of if( newnode ==NULL) } void ListBuild::findpr()const { if (sz==0) cout<< "already empty list"<<endl; else if(sz==1) { } // do nothing else { list prev = head; for (int i=0;i<sz-1;i++) { prev= prev->next; } } } void ListBuild ::remove() // remove item { --sz; if (sz==0) cout<< "already empty list"<<endl; else if (sz==1) // delete first node { delete tail; tail=NULL; } else // delete rest nodes { list curr; curr= prev->next; // now points to node be deleted prev->next = curr->next; curr=NULL; delete curr; } } void ListBuild ::print() { list temp=NULL; temp=head; // dont want to change head pointer, so create another temp //pointer for (int i=0;i<sz;i++) { cout<< temp->d<<'\t'; temp=temp->next; } }
.Code:#include <iostream> #include "Link_list_build.h" using namespace std; int main() { ListBuild a,b,c ; a.insert(10); // insert at start a.print(); b.insert(20); // insert at end and build list b.print(); c.insert(30); c.print(); }
the code compiles and allocates first node. but, as i pass second node data, it reaces
within "insert" function and gives memory access violation.tail->next = newnode;
any ideas why? I do not see why it should.
I also had other question,while copying code here, how do i copy line numbers ?
thanks
sedy



LinkBack URL
About LinkBacks


