Re: [Dev-C++] Linked List and Pointers
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
From: Michal M. <mol...@se...> - 2011-05-02 06:30:58
|
Sorry for the formatting Dne 2.5.2011 4:33, Jordan Burnam napsal(a): > void linklist::append(int num) > { > node *newNode = new node; > node *nextNode = new node; > if (p == NULL) > { > p = newNode; > p ->data = num; > p->link = NULL; > } > > else { // missing > newNode = new node; > node * n = p; > while(n -> link){n = n -> link;} > n-> link = newNode; > > newNode -> data = num; > newNode -> link = NULL; } // missing > } > void linklist::next( int c, int num) > { > node *lastNode; you never read value of lastNode so can get rid of it > node *currNode; > node *nextNode; > > currNode = p; > lastNode = currNode; > nextNode = currNode -> link; the line above will fail if the list is empty, you should check that situation > > while(c != 0) > { > lastNode = currNode; > currNode = currNode -> link; > nextNode = currNode -> link; > c--; OK, but you should check if you are still inside the list if (currNode == NULL) { cerr << "linklist::next: outside the list" << endl; return; } > } > > node *newNode; > newNode = new node; > newNode -> data = num; > > currNode -> link = newNode; > newNode -> link = nextNode; > > } void linklist::del( int num ) { node * lastNode; node * currNode; currNode = p; lastNode = NULL; while(currNode != NULL) { if(currNode -> data == num) { if (lastNode) { lastNode->link = currNode->link; delete currNode; } else { // it was the first node in the list node* n = p; p = p->link; delete n; } return; } else { // should be here although it accidentally works even without them lastNode = currNode; currNode = currNode -> link; } // should be here although it accidentally works even without them } // if } // while cout << "Item not found" << endl; } > void linklist::display() should be OK int linklist:: count () { int count =0; node *a_node; a_node = p; while(a_node != NULL) { count++; a_node = a_node -> link; } return count;} |