samedi 27 juin 2015

C++ linked list values changing retroactively

I am trying to implement a linked list class that utilizes a node class as defined in the assignment. The below code block prints output as expected:

#include <iostream>
using namespace std;

// Node class as provided
class node {
    void *info;
    node *next;
public:
    node (void *v) {info = v; next = 0; }
    void put_next (node *n) {next = n;}
    node *get_next ( ) {return next;}
    void *get_info ( ) {return info;}
};

// Linked list class
class list {
    //Start of the linked list
    node *start;
public:
    list (int v) {
        start = new node (&v);
    }

    void insert (int value, int place=-1) {
        node *temp = new node (&value);

        if (place == 0) {
            temp->put_next(start);
            start = temp;
        } else {
            node *before = start;
            for (int i = 1; before->get_next() != 0; i++) {
                if (i == place) { 
                    break;
                }
                before = before->get_next();
            }

            temp->put_next(before->get_next());
            before->put_next(temp);
        }
    }

    void remove(int place) {
        if (place == 0) {
            start = start->get_next();
        } else {
            node *curr = start;
            for (int i = 1; curr != 0; i ++) {
                if (i == place) {
                    curr->put_next(curr->get_next()->get_next());
                    break;
                }
                curr = curr->get_next();
            }
        }
    }

    void display() {
        for (node *current = start; current != 0; current = current->get_next()) {
            cout << *(static_cast<int*>(current->get_info())) << endl;
        }
    }
};

int main() {

    list *tst = new list(10);
    tst->display();
    cout << "Prepending 9" << endl;
    tst->insert(9,0);
    tst->display();
    cout << "Inserting 8" << endl;
    tst->insert(8,1);
    tst->display();
    cout << "Prepending 7" << endl;
    tst->insert(7,0);
    tst->display();

    tst->remove(0);

    cout << "Removed the first element:" << endl;
    tst->display();
    cout << endl;

//  cout << "Prepending 6" << endl;
//  tst->insert(6,0);
//  tst->display();

}

Creates this output:

10
Prepending 9
9
10
Inserting 8
9
8
10
Prepending 7
7
9
8
10
Removed the first element:
9
8
10

However, when I add this last statement to the end of the program flow in main:

tst->insert(6,0);

My output changes to this:

10
Prepending 9
9
10
Inserting 8
8
8
10
Prepending 7
7
7
7
10
Removed the first element:
134515798
134515798
10

What am I missing? How can adding a value later in execution change the output that happens before I even get to that point in the program flow?

I am using ideone.com as my IDE/to run the program, I've never had an issue before, but is that the issue?

Aucun commentaire:

Enregistrer un commentaire