single linked list!!!
Jan 26, 2013 at 9:41pm Jan 26, 2013 at 9:41pm UTC
I am trying to build a bag class with single linked list!!
I tested my code but I think there is something long with connecting the nodes by using pointers!
Anyone see the problems??
Header file!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#ifndef BAG_H_
#define BAG_H_
#include <iostream>
using std::string;
class bag{
public :
bag();
void push_back(bag*& head_ptr, string str);
bool search(bag*& head_ptr, string target);
void show(bag*& head_ptr);
void remove(bag*& head_ptr);
private :
bag* link;
string name;
size_t length;
};
#endif /* BAG_H_ */
cpp file!!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include "bag.h"
#include <iostream>
using std::string;
using std::cout;
using std::endl;
bag::bag(){
link = NULL;
name = "" ;
length = 0;
}
void bag::push_back(bag*& head_ptr, string str){
if (head_ptr == NULL){
head_ptr = new bag();
head_ptr->link = NULL;
head_ptr->name = str;
head_ptr->length++;
}
else {
bag* temp = NULL;
temp = head_ptr;
bool truth = true ;
while (truth){
if (temp == NULL){
truth = false ;
break ;
}
temp = temp->link;
}
temp = new bag();
temp->link = NULL;
temp->name = str;
temp->length++;
}
}
void bag::remove(bag*& head_ptr){
while (true ){
bag* temp = head_ptr;
head_ptr = temp->link;
if (head_ptr == NULL){
return ;
}
delete temp;
}
}
void bag::show(bag*& head_ptr){
for (bag* cursor = head_ptr; cursor!=NULL; cursor = cursor->link){
cout<<"name = " <<cursor->name<<"length = " <<cursor->length<<endl;
}
}
Jan 26, 2013 at 10:31pm Jan 26, 2013 at 10:31pm UTC
You never link the cells.
When the loop 25 ends, `temp' will be NULL. Immediately you set it to a new allocated object.
What you need to do:
Get to the last cell and do
last_cell.link = new node;
It's simpler if you use an empty header cell and a circular list
http://www.cplusplus.com/forum/beginner/90716/#msg487820
Also, you may want to distinguish an `element' from a `container'
Last edited on Jan 26, 2013 at 10:31pm Jan 26, 2013 at 10:31pm UTC
Jan 30, 2013 at 5:34am Jan 30, 2013 at 5:34am UTC
thank you!!
Topic archived. No new replies allowed.