Friday 15 February 2013

c++ - Pointer in linked list/vector -



c++ - Pointer in linked list/vector -

i'm trying implement own linked list using vectors , pointers. problem i'm have can't first node point sec node.

here's code , i've tried:

struct node { node* previous; node* next; int data; }; // initialize: create vector size 20 , first node void linkedlist::init() { veclist.resize(20, null); // vector of size 20 node* head = new node(); // create head node head->previous = null; // previous point set null head->next = veclist[1]; // next pointer set next position head->data = 0; // info set @ value 0 veclist[0] = head; // set head node in first position count = 1; // increment count 1 } // add together node array void linkedlist::push_back(node* node, int data) { count += 1; node = new node(); node->next = veclist[count + 1]; node->previous = veclist[count - 1]; node->data = data; veclist[count - 1] = node; }

the info has been passed in , displayed using:

cout << linkedlist.veclist[1]->data << endl;

but if seek way display error saying next pointer <unable read memory>

cout << linkedlist.veclist[0]->next->data << endl;

you forgot set next pointer of previous node in push_back method. if count fellow member variable of list containing number of entries have alter method this:

edit: have increment count in end because array indices start zero.

void linkedlist::push_back(node * node, int data){ node = new node(); node->next = null; // null because next element not exist yet node->previous = veclist[count - 1]; node->data = data; veclist[count] = node; veclist[count-1]->next = veclist[count]; count++; }

still it's bit unusual seek implement linked list vector or array because defeats advantages of list...

c++ pointers vector linked-list

No comments:

Post a Comment